【问题标题】:How to Pass JSON Data into Express REST API如何将 JSON 数据传递到 Express REST API
【发布时间】:2020-05-31 07:57:17
【问题描述】:

我正在使用 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 json = require("./jsonFile")。然后根据需要使用它
  • 如果您不想将任何更新写入磁盘,这将起作用
  • 谢谢罗杰,所以如果我想从桌面上的路径访问它,我只是把它作为要求的参数?例如: const json = require("Desktop/jsonFile") 还是它必须在项目目录中?

标签: javascript node.js json rest express


【解决方案1】:
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.
}
    });

【讨论】:

  • 好的 - 在使用 stringify 之后,使用某种正则表达式或解析函数来分解 JSON 文件中的数据是否有意义(这是我最终想要完成的)?该文件有一个 ID、汽车类型和颜色,但我想从 JSON 文件中获取特定数据
  • 我会在 stringify 之前处理数据,您将使用 JSON.parse(JSONfile) 这将允许您使用点符号来更改对象键/值对。
  • 另外,在你的路由中使用 try catch。现在,如果出现故障,您的路线将挂起。
  • 您能否提供一个示例来说明如何执行此操作或更具体的含义?
  • 非常感谢。您的评论已经非常有帮助,但我只是没有完全遵循 try/catch (感觉这可能是一个我花了很多时间但有点超出我的主要目的的兔子洞,所以我只是想获取有关您的意思的更具体的细节)。
【解决方案2】:

一种选择是使用节点 fs(文件系统)。

一种选择是将端点转换为异步函数。

在每个请求中,使用 fs.open() 打开文件。根据您的要求,读取整个文件或提供要读取的偏移量。

然后用JSON.parse()解析数据,格式化并返回。


另一种选择是在启动时执行上述所有步骤,将文件的内容保存到某种存储中。然后你可以绕过请求处理中从磁盘读取的慢速。

这是来自节点docs 的一些示例代码。我建议您查看不同的选项。

我还建议使用返回承诺(或承诺回调)的方法。这样你访问它的代码就可以有一个干净的顺序。

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.fstat(fd, (err, stat) => {
    if (err) throw err;
    // use stat

    // always close the file descriptor!
    fs.close(fd, (err) => {
      if (err) throw err;
    });
  });
});

【讨论】:

  • 谢谢 - 这对于这项任务来说似乎有点复杂(即使用 fs),但也许这正是我们所需要的。我将查看 Node 文档,看看还有什么。
猜你喜欢
  • 1970-01-01
  • 2021-07-27
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 2019-07-01
  • 2015-01-03
  • 2014-08-11
相关资源
最近更新 更多