gpt4 book ai didi

javascript - 如何将 JSON 数据传递到 Express REST API

转载 作者:太空宇宙 更新时间:2023-11-03 23:11:51 25 4
gpt4 key购买 nike

我正在使用 Node/Express 创建 REST API,并且有一个关于设置 API 以及如何将 JSON 文件合并到其中的问题。以下是我想要查找的 JSON 数据的示例,其中包括 ID 号、型号和颜色:

{ “1”:{ "car_model": "法拉利", “颜色”:“银色” }, “2”:{ "car_model": "保时捷", “颜色”:“绿色” }, “3”:{ "car_model": "凯美瑞", “颜色”:“蓝色” }}

现在,我想让 GET 路由返回 JSON 列表中的所有汽车,并返回 ID、颜色和型号。我不确定如何将 JSON 数据合并到请求中(假设它位于我的硬盘上的路径/JSON)

我将以下代码设置为 API 的基础:

// BASE SETUP
// =============================================================================

// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080; // set our port


// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/endpoint_get', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

router.post('/endpoint_post', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});


// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /endpoint.com
app.use('/endpoint.com/', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

不一定使用此代码,我希望任何人提供一些指导或帮助,或者提供如何将 JSON 数据(来自某个随机文件)合并到 HTTP 请求中的示例。谢谢

最佳答案

const jsonDoc = require('../Desktop/jsonDoc.json');// top of file...


router.get('/endpoint_get', function(req, res) {
try{
let jsonObj = JSON.parse(jsonDoc) /*{ "1": { "car_model": "Ferrari", "color": "Silver" }, "2": { "car_model": "Porsche", "color": "Green" }, "3": { "car_model": "Camry", "color": "Blue" } }*/
console.log(jsonObj)

res.json({
message: 'hooray! welcome to our api!',
jsonDoc:JSON.stringify(jsonObj)
});
/* returns {
"message": "hooray! welcome to our api!",
"jsonDoc": { "1": { "car_model": "Ferrari", "color": "Silver" }, "2": { "car_model": "Porsche", "color": "Green" }, "3": { "car_model": "Camry", "color": "Blue" } }
}*/

}catch(error){ /* now if anything above fails a error code can be returned to the caller and debug info can be sent to the developer*/
console.trace(error);// trace out the error.
res.sendStatus(500)// return error code to user.
}
});

关于javascript - 如何将 JSON 数据传递到 Express REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60244594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com