0

当我转到 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)
4

1 回答 1

0

首先,您的 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);
于 2021-01-31T13:48:47.880 回答