fetch api 不发送数据
fetch api doesn't send data
我的客户端应用程序在到达服务器时不发送数据并显示 undefined
。我对 node 和 fetch api 作为一个整体还很陌生。当我单击前端的按钮时,它应该触发 signin()
并发送用户名('robot')和密码('cookies'),但它不起作用并且输出在终端。
服务器
var database = [
{
name: 'robot',
password: 'cookies'
}
];
app.post('/signin',(req,res)=>{
let username = req.body.username;
let password = req.body.password;
database.map((user,i) =>{
if (username === database[i].name &&
password === database[i].password) {
res.json('success');
}else{res.json("Login fail");console.log(req.body.username+":user:",req.body.username+":pass:");
}
});
});
前端
signIn() {
console.log('SignIn function called');console.log("Password: ",this.state.password);console.log("Username: ",this.state.username);
fetch('http://localhost:3000/signin',{
method:'post',
header:{'Content-Type':'application/json'},
body: JSON.stringify({
username:this.state.username,
password:this.state.password
})
})
.then(r => r.json())
.then(d => {
if (d === 'success'){
console.log("Login succesfull");
}else{
console.log("Failed");
}
})
}
您在前端代码中输入错误。 fetch
api 有 headers
字段,而不是 header
。
fetch('http://localhost:3000/signin',{
// other code
headers: {
'Content-Type':'application/json'
},
})
我的客户端应用程序在到达服务器时不发送数据并显示 undefined
。我对 node 和 fetch api 作为一个整体还很陌生。当我单击前端的按钮时,它应该触发 signin()
并发送用户名('robot')和密码('cookies'),但它不起作用并且输出在终端。
服务器
var database = [
{
name: 'robot',
password: 'cookies'
}
];
app.post('/signin',(req,res)=>{
let username = req.body.username;
let password = req.body.password;
database.map((user,i) =>{
if (username === database[i].name &&
password === database[i].password) {
res.json('success');
}else{res.json("Login fail");console.log(req.body.username+":user:",req.body.username+":pass:");
}
});
});
前端
signIn() {
console.log('SignIn function called');console.log("Password: ",this.state.password);console.log("Username: ",this.state.username);
fetch('http://localhost:3000/signin',{
method:'post',
header:{'Content-Type':'application/json'},
body: JSON.stringify({
username:this.state.username,
password:this.state.password
})
})
.then(r => r.json())
.then(d => {
if (d === 'success'){
console.log("Login succesfull");
}else{
console.log("Failed");
}
})
}
您在前端代码中输入错误。 fetch
api 有 headers
字段,而不是 header
。
fetch('http://localhost:3000/signin',{
// other code
headers: {
'Content-Type':'application/json'
},
})