【发布时间】:2020-02-18 03:52:20
【问题描述】:
我正在运行一个使用 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'
【问题讨论】:
标签: javascript node.js reactjs