【发布时间】:2020-09-01 20:31:58
【问题描述】:
我尝试在邮递员中发布数据,它返回一个 json 对象,这些方法运行良好。 当 api 以 json object 响应时,我在获取属性值时遇到问题。 json的格式是这样的:
{
"success" : "true"
}
api方法:
router.post("/sickers/user/login/", (req, res) => {
var values = JSON.parse(req.body);
var pass = values.password;
var email = values.email;
//console.log(values);
if (pass !== null || pass !== "") {
try {
con.connect();
con.query("SELECT Password FROM `sickers` WHERE Email='" + email + "'", function(err, rows, field) {
if (err) {
console.log(err);
res.send("an error detected try later");
} else {
try {
if (pass == rows[0].Password) {
//trying to send correct message from here
res.send({ success: "true" });
console.log("yes")
} else {
console.log("no")
res.send({ success: "false" });
}
} catch {
console.log("no")
res.send({ success: "false" });
}
}
});
} catch (e) {
res.send("no data found");
console.log("obj not found");
}
}
con.end();
});
react 应用的 post 方法是:
//submit values
async submithandler(e) {
e.preventDefault();
try{
await fetch('http://localhost:8000/api/sickers/user/login/',{
method:'post',
mode:'no-cors',
headers:{
'Accept':'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
password:this.state.password,
email:this.state.email
})
})
.then(response=>{
this.setState({data:response})
alert(data.success);
})
}catch(e){
alert(e)
}
}
状态中的数据声明:数据:[] 错误是数据未定义。
【问题讨论】:
-
看看here
.then(response => response.json()).then(data => ... -
这能回答你的问题吗? Using Fetch API to Access JSON
-
感谢您的回复,您提到的方法是正确的并且有效,但我对
response.json()有疑问,它向我显示 Unhandled Rejection (SyntaxError): Unexpected end of input 每个我用它的时间。