【问题标题】:Why use response.json() on both server and client side to access json object为什么在服务器端和客户端都使用 response.json() 来访问 json 对象
【发布时间】:2017-05-05 19:12:15
【问题描述】:

我是 MEAN 堆栈的新手, 这是我的 API,我使用 res.json(random) 发送随机密码

module.exports.changePass = function (req, res) {
    console.log(req.body.email)

db.user.find({ where: { name: req.body.name, email: req.body.email } }
    ).then(function (result) {
        if (result == null) {
            res.statusCode = '400'
            res.json({
                'error': 'Bad request, user not found'
            })
        } else {
            var random = Math.random().toString(36).slice(-8);
            result.updateAttributes({
                password: random
            }).then(function (result) {
                res.statusCode = '200';
                res.json(
                    random
                );
            });
        }
    });
}

这是客户端代码(Angular),我使用了 response.json() 以便我可以访问该随机密码

    this.http.post('http://localhost:3000/fp',
 { name: this.name, email: this.email })
.toPromise().then((response) => {
            alert('fp successful. ' + response.json());
          }).catch((error: any) => {
            if (error.status === 400) {
              alert("User not found");
              return Observable.throw(new Error(error.status));
            }
          });

我的问题是,当我从服务器作为 json 发送响应时,为什么我们必须在客户端再次将该响应转换为 json 以访问该对象?

【问题讨论】:

  • 因为你在提醒它。警报使用字符串。提醒对象没有用。
  • 因为它是一个字符串,你没有传递一个对象。

标签: javascript angularjs json express mean-stack


【解决方案1】:

JSON 是一种基于文本的格式。 response.json 函数调用可能会将 JavaScript 对象转换为字符串并设置正确的 mime 类型。根据您在客户端使用的库,是否可以自动解析它(如 jQuery)。

【讨论】:

  • 我的问题被否决了,你的回答被否决了,:/
  • @DaniyalJavaid 哦,好吧。希望我的回答对你有帮助。
猜你喜欢
  • 2011-07-04
  • 2021-01-30
  • 1970-01-01
  • 2023-02-26
  • 2021-10-01
  • 1970-01-01
  • 2013-11-16
  • 2012-05-19
  • 1970-01-01
相关资源
最近更新 更多