在NodeJs中读取JSON时,对象为null
我运行了这个服务器代码在NodeJs中读取JSON时,对象为null,json,node.js,Json,Node.js,我运行了这个服务器代码 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.p
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时代码>对象用户
为空
我会错过一个模块吗?代码是否错误?用户对象为空,因为您在代码实际读取文件之前返回它
fs.readFile('./database.json', 'utf8', function (err, data) { }
fs.readFile是异步的,因此为了返回正确的值,必须将return语句移动到fs.readFile块中
此外,由于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
});
});
}
用户对象为空,因为您在代码实际读取文件之前返回它
fs.readFile('./database.json', 'utf8', function (err, data) { }
fs.readFile是异步的,因此为了返回正确的值,必须将return语句移动到fs.readFile块中
此外,由于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
});
});
}
请检查编辑。在您的代码中,res.json在“getUserById”返回实际值之前返回。请检查编辑。在代码中,res.json在“getUserById”返回实际值之前返回。