当我转到URL时/user/:id
,我想检索有关该ID的所有信息作为响应。
这是data.json
:
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
}
这是index.js
:
var express = require('express');
var app = express();
app.get('/user/:id', function(req, res) {
// do stuff here
})
app.listen(3000)
首先,您的JSON必须是一个数组,因此将其更改为
[
{
"id": 1,
"name" : "name1"
},
{
"id" : 2,
"name" : "name2"
}
]
然后在你的快递中
var express = require('express');
var fs = require('fs'); // util to read file
var app = express();
/**
JSON.parse is a function to parse string with JSON format to JavaScript object
fs.readFileSync is a function to read file synchronously, first parameter is the path to the file,
second parameter is the encoding type
*/
var users = JSON.parse(fs.readFileSync('path/to/data.json', 'UTF-8'));
// users now is [{ id: 1, name : "name1" }, { id : 2, name : "name2" }]
// users[0].name will gives you name1
app.get('/user/:id', function(req, res) {
var id = +req.params.id; // will contains data from :id, the + is to parse string to integer
var user = users.find(u => u.id === id); // find user from users using .find method
res.send(user); // send the data
})
app.listen(3000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句