json - 在 NodeJs 中读取 JSON 时,对象为 null

标签 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.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/

相关文章:

javascript - 如果从 JSON.search() 返回 JavaScript 变量,为什么它是 "undefined"?

javascript - 在 JavaScript 中计算 JSON 文件中键值对的实例

java - Spring MVC MappingJackson2JsonView 集合元素重复

node.js - 自 Node v0.12.2 起的负载均衡 - 集群、pm2 或 nginx

javascript - 值未保存在 orientdb 类中

javascript - ember-data 悲惨错误重复记录

java - 创建 JSONObject 时 org.json 未报告的异常

mysql - 正确删除 Go 中的第二个 json.Marshal

javascript - 无法停止nodejs中的递归settimeout函数

node.js - 从nodejsexpress登录cakephp