我运行了此服务器代码
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/profile/:id', function (req, res) { // A route with a parameter
res.render('profile', {
user: getUserById(req.params.id)
});
});
app.listen(8888, function () {
console.log('Server running on port 8888');
});
function getUserById(userId){
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data);
var users = json.users;
return users.find(u => u.id === userId);
});
}
当调用路由时,函数getUserById
被调用。在我的数据库中,我有这些数据
{
"users": [
{
"id": 2312,
"name": "Foo Bar",
}
]
}
例如,路线为 /profile/2312
。
req.params.id
返回值 2312。
在var currentUser = users[0];
处的循环中currentUser.id
会返回2312,传入的参数为2312。
但是当分配user = currentUser;
时,对象user
为空。
我错过了某个模块吗?代码有错吗?
最佳答案
用户对象为空,因为您在代码实际读取文件之前返回它。
fs.readFile('./database.json', 'utf8', function (err, data) { }
fs.readFile 是异步的,因此为了返回正确的值,您必须将 return 语句移至 fs.readFile block 内。
此外,由于 getUserById 正在调用异步函数,因此您必须在“getuserById”执行完成后调用 res.render。
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/profile/:id', getUserById);
app.listen(8888, function () {
console.log('Server running on port 8888');
});
function getUserById(req,res){ // Get a user from the database by userId
const userId = req.params.id;
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // get the JSON object
var users = json.users; // convert the object to a user array
var match = users.find(u=>u.id.toString()===userId.toString());
//Call render after the asynchronous code finishes execution.
res.render('profile', {
user: match
});
});
}
How does Asynchronous Javascript Execution happen? and when not to use return statement?
关于json - 在 NodeJs 中读取 JSON 时,对象为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47437929/