首先,您的 JSON 必须是一个数组,因此将其更改为
[
{
"id": 1,
"name" : "name1"
},
{
"id" : 2,
"name" : "name2"
}
]
然后在你的快递 csode 上
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);