[英]Promise rejected in POST login using fetch API in reactjs and Nodejs
I am working on a simple login using POST Fetch in Reactjs with NodeJs API.我正在使用带有 NodeJs API 的 Reactjs 中的 POST Fetch 进行简单的登录。 The code is working good and redirect the page when we login using correct username and password but the problem is when using fake username.
当我们使用正确的用户名和密码登录时,代码运行良好并重定向页面,但问题在于使用假用户名时。 I got the error in console.log with Promise : "Rejected".
我在console.log 中收到了Promise 错误:“已拒绝”。 And I still can not figure it why
我还是想不通为什么
Here is the code in login.js这是 login.js 中的代码
async SubmitLogin(event){
event.preventDefault();
//debugger;
console.log(this.state)
await fetch(`http://localhost:4000/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(this.state)
})
.then ((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
// then Read the response as json.
else {
let result = response.json();
console.log(result)
if(result === 'Invalid'){
console.log(response)
alert('Invalid User');
//this.props.history.push('/login');
}
else {
alert('Login Sucessfull');
this.props.history.push('/home');
}
}
})
.catch((err) => {
console.error();
})
}
in my server.js, I used express-session like this:在我的 server.js 中,我使用了这样的 express-session:
//sales login
app.post('/login', jsonParser, (req, res) => { //jsonParser,
let username = req.body.username;
let password = req.body.password;
console.log("req: ",req.body);
if (username && password) {
dbConn.query(`SELECT * FROM user_tbl WHERE username = ? AND password = ?`, [username, password], (err, results, fields) => {
if (results.length > 0) {
req.session.loggedin = true;
req.session.username = username;
res.redirect('/home');
console.log(results)
console.log("req: ", req.body);
} else {
res.send('Incorrect Username and/or Password!');
}
res.end();
});
} else {
res.send('Please enter Username and Password!');
res.end();
}
});
app.get('/home', (req, res) => {
if (req.session.loggedin) {
res.send('Welcome back, ' + req.session.username + '!');
} else {
res.send('Please login to view this page!');
}
res.end();
});
and this is the result I got in console:这是我在控制台中得到的结果:
hopefully my question is clear.希望我的问题很清楚。
I think your response doesnt come json format.You cant parse string to json.我认为您的回复不是 json 格式。您无法将字符串解析为 json。
Your response should be like this res.send({success:false , message : "Incorrect Username and/or Password!"})
您的回复应该是这样的
res.send({success:false , message : "Incorrect Username and/or Password!"})
After many suggestions and anwers, finally I can figure out how to solved this problem.经过多次建议和回答,我终于可以弄清楚如何解决这个问题。 Here is the code in login.js
这是 login.js 中的代码
//submit function
async SubmitLogin(event){
event.preventDefault();
console.log(this.state)
await fetch(`http://localhost:4000/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(this.state)
})
.then ((response) => {
if(response.status === 401) {
throw new Error('Unauthorized');
}
//return response.json();
})
.then((result) => {
console.log(result);
this.props.history.push('/home');
alert('Login Sucessfull');
})
.catch((err) => {
console.log();
})
}
and in the backend, I didn't change anything.在后端,我没有改变任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.