【发布时间】: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