【发布时间】: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