Reputation: 11
I have a question. In the client side, I use fetch API to get response, this is the code
window.fetch('/signup', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formDataStr,
credentials: 'same-origin'
})
.then(function (response) {
return response.json()
})
.then(function (result) {
if (result.code === 0) {
return this.$router.push('/main')
}
})
.catch((err) => {
self.isLoading = false
console.log(err)
})
In the server, it is written in node and express, this is the code:
`app.post('/login', function (req, res) {
var loginEmail = req.body.email2
var loginPsd = req.body.secret
UserDataModel.findOne({ email: loginEmail }, {
name: 1,
password: 1,
email: 1
}, function (err, userInfo) {
if (err) {
console.log(err)
}
if (!userInfo) {
res.send({
code: -1,
msg: 'user not exist'
})
return console.log('user not exist')
}
userInfo.comparePassword(loginPsd, function (err, isMatch) {
if (err) {
console.log(err)
}
if (isMatch) {
req.session.isLogin = true
req.session.userInfo = {
userName: userInfo.name,
userEmail: userInfo.email
}
console.log(req.session)
res.json({
code: 0,
msg: 'login succeed!'
})
res.end()
} else {
res.send({
code: -2,
msg: 'wrong password'
})
}
})
})
})`
The console shows that post is successful with status code 200. However, the fetch next then promise can not execute. It seems that there is no response from server.
Upvotes: 1
Views: 2766
Reputation: 2197
You client-side code is sending an HTTP POST request to /signup
, but your server side code is set up to receive POST requests at /login
. Those URLs need to match, if you want your server to handle those requests from your client.
Upvotes: 0
Reputation: 14982
You use this
inside a function. It refers to global object.
Try:
.then(function (result) {
console.debug(result); // inspect a result
if (result.code === 0) {
return self.$router.push('/main'); // assume you have var self = this above.
}
Promise.reject(new Error('Error code: ' + result.code)); // generate an error
})
Upvotes: 1