我无法将简单的json数据从javascript ajax客户端发送到nodejs express rest api。
这是服务器端代码:
//POST api/login
app.post('/api/login', (req, res) => {
console.log(req.body)//here the body always empty object
var body = _.pick(req.body, ['email', 'password'])
console.log(body)
var user;
User.findByCredentials(body.email, body.password).then((result) => {
user = result
return user.generateAuthToken()
}).then((token) => {
res.status(200).header('x-auth', token).send(user)
}).catch((e) => {
res.status(400).send('Unauthorized')
})
})
这是客户端:
$(document).ready(function(){
jQuery('#login-form').on('submit', function(e){
e.preventDefault()
var username = jQuery('[name=username]').val()
var password = jQuery('[name=password]').val()
if(username && password){
let dataToSend = {
"email":username,
"password":password
}
console.log(dataToSend)
$.ajax({
url:"http://192.168.1.22:3000/api/login",
type: "POST",
data: dataToSend,
headers: {
'Access-Control-Allow-Origin':"*",
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json'
},
dataType: 'json',
cache: false,
success: function(data){
console.log('on success : '+data);
},
error: function(e){
console.log("login error, status: "+e.status +" message :
"+e.responseText);
}
})
}
})
})
问题是,如果我这样发送请求,则会在服务器端出现崩溃错误:
SyntaxError: Unexpected token e in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (D:\NodeJs-Projects\location-tracker-server\node_modules\body-parser\lib\types\json.js:158:10)
at parse (D:\NodeJs-Projects\location-tracker-server\node_modules\body-parser\lib\types\json.js:83:15)
at D:\NodeJs-Projects\location-tracker-server\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (D:\NodeJs-Projects\location-tracker-server\node_modules\raw-body\index.js:224:16)
at done (D:\NodeJs-Projects\location-tracker-server\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (D:\NodeJs-Projects\location-tracker-server\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
如果我从请求中删除标头数据,它不会崩溃,但是我总是在服务器上收到空的正文,而最烦人的是,如果我从带有okHttp库的android native客户端发出相同的请求,则一切正常。 我想念什么吗?
答案 0 :(得分:0)
好吧,经过许多组合之后,我解决了它,由于某种原因,只有在我调用JSON.stringify(dataToSend)
并将contentType: "application/json;charset=utf-8"
添加到请求后,我才能够在服务器上成功接收数据。
我仍然不清楚为什么需要stringify
数据。
完整的客户代码:
$(document).ready(function(){
jQuery('#login-form').on('submit', function(e){
e.preventDefault()
var username = jQuery('[name=username]').val()
var password = jQuery('[name=password]').val()
if(username && password){
let dataToSend = {
"email":username,
"password":password
}
dataToSend = JSON.stringify(dataToSend)
console.log(dataToSend)
$.ajax({
url:"http://192.168.1.22:3000/api/login",
method: "POST",
data: dataToSend,
contentType: "application/json;charset=utf-8",
dataType: 'json',
cache: false,
success: function(data){
console.log('on success : '+data);
},
error: function(e){
console.log("login error, status: "+e.status +" message : "+e.responseText);
}
})
}
})
})