javascript - 与 Node 反应,从 res.status.json() 获取 json 数据
问题描述
我正在运行一个使用 nodejs 作为 api 连接到我的数据库的反应应用程序。
对于我的登录,我将数据发送到服务器,它返回通过或失败。
但是我不确定如何提取这个 json 对象。
我查看了请求和响应,当我操纵 json 对象时,响应内容长度一直在变化,所以我相信它一定在某个地方。
服务器代码:
app.post('/api/checkLogin', async (req,res) => {
console.log(req.body);
const {username, password} = req.body;
try{
let state = await DB.checkPassword(username, password);
console.log(state);
if(!state){
res.status(401).json({
error: 'Incorrect username or password',
yay: 'idk work?'
});
}
else if(state){
res.status(200).json({
message: 'we in boys'
});
} else {
res.status(6969).json({
err: 'idk mane'
});
}
} catch(e) {
console.log(e);
}
})
客户代码:
onSubmit = (event) => {
event.preventDefault();
fetch('/api/checkLogin', {
method:'POST',
body: JSON.stringify({username: this.state.username, password: md5(this.state.password)}),
headers: {
'Content-Type':'application/json'
}
}).then(res => {
if(res.status ===200) {
this.props.loggedIn();
} else if(res.status ===401){
console.log(res.status);
alert('wrong username or password');
}else{
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.log(err);
alert(err);
});
}
作为一种提取数据的方式,我有点期待。
在服务器上:
res.status(200).json({ message : 'mssg'});
在客户端:
console.log(res.status.message) // 'mssg'
解决方案
感谢 Jin 和我找到的这篇文章帮助Fetch API 从响应中获取原始值
我发现两者都
res.status(xxx).json({ msg: 'mssg'})
有效res.status(xxx).send({msg: 'mssg'})
。
然后可以使用嵌套的承诺在客户端解释 json 或发送的消息。这是用...完成的
fetch('xxx',headers n stuff).then(res => {
res.json().then((data) => {console.log(data.message)});
//'mssg'
res.text().then((data) => { let data1 = JSON.parse(data); console.log(data1.message);});
//'mssg'
});
推荐阅读
- sql - SQL 错误:从字符串转换日期和/或时间时转换失败
- authentication - {"detail": "未提供身份验证凭据。"} 邮递员和 DRF
- python-3.x - XGboost 自定义物镜。梯度和黑森问题
- php - 图像 [类型] 上传上的 Ckfinder 致命错误 [不支持的图像类型(非资源):图像/jpeg]
- java - 使用 getResourceAsStream 的输入流返回 null
- c++ - C ++:如何将数组传递给类的实例并获取 sizeof() 它?
- kubernetes - K8S ceph csi rbd 如何从现有 RBD 映像创建持久卷
- python - 为什么 plt.show() 不起作用。文件名report.py
- python - 用 Python 修改 .bash_aliases
- javascript - 从 userScript 填充 Material Web Components 文本字段