我正在运行一个 React 应用程序,其中 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 get raw value from Response
我发现两者
res.status(xxx).json({ msg: 'mssg'})
和 res.status(xxx).send({msg: 'mssg'})
有效。
然后可以使用嵌套的 Promise 在客户端解释 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'
});
关于javascript - React 与 Node 从 res.status.json() 获取 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58496771/