【问题标题】:ExpressJS - What happens when .json() is used in with a response?ExpressJS - 当 .json() 与响应一起使用时会发生什么?
【发布时间】:2019-01-23 16:25:11
【问题描述】:

我正在使用 ExpressJS 制作服务器,这件事真的让我很烦。在我的回复中使用 .json() 而不是 .send() 有什么用。根据 Express 的说法,.send() 会自动将 JavaScript 对象转换为 JSON 字符串,我们不需要使用 stringify。那为什么要在我的响应中使用 .json()。

app.get('/profile/:id', (req, res) => {
const {id} = req.params;
let found = false;
database.users.forEach(user => {
    if(user.id === id) {
        found = true;
        return res.json(user);
    }
})
if (found === false)
{
    res.status(400).json('not found');
}
})

这是 res.json() 出现的代码。

【问题讨论】:

    标签: json node.js express server


    【解决方案1】:

    最后res.json 调用res.send,当你传递一个对象或数组时它们都是相同的。

    但res.json 方法也使用json replacer 和json spaces 设置。它们为您提供更多的灵活性和选项来格式化您的 json 文件。 res.json 也确保响应是 utf8 字符集。

    为了更好地理解差异,我建议您检查: Difference between res.send and res.json in Express.js

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 2020-12-06
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 2015-01-23
      • 1970-01-01
      相关资源
      最近更新 更多