Reputation:
My client side app doesn't send the data and show undefined
when it reaches the server. I'm fairly new to node and fetch api as a whole. When I click a button on the front end, it should fire the signin()
& send username('robot') & password('cookies') but it doesn't work and output show undefined in the terminal.
SERVER
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:");
}
});
});
FRONT-END
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");
}
})
}
Upvotes: 0
Views: 1212
Reputation: 9022
You have typing error in front-end code. fetch
api has headers
field, not header
.
fetch('http://localhost:3000/signin',{
// other code
headers: {
'Content-Type':'application/json'
},
})
Upvotes: 2