简体   繁体   English

Node.js快速发布请求中的请求正文为空

[英]Request body is empty in nodejs express post request

i have troubles to send simple json data from javascript ajax client to nodejs express rest api. 我很难将简单的json数据从javascript ajax客户端发送到nodejs express rest api。

Here is the server side code: 这是服务器端代码:

    //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')
  })

})

Here is the client side: 这是客户端:

$(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);
        }
      })
    }
  })
})

The problem is if i send the request like this i get crash error on server side : 问题是,如果我发送这样的请求,则会在服务器端出现崩溃错误:

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)

If i remove the headers data from request it will not crash but i always receive empty body at server, and the most annoying is if i make the same request from android native client with okHttp library all work perfect. 如果我从请求中删除标头数据,它不会崩溃,但是我总是在服务器上收到空的正文,而最令人讨厌的是,如果我从带有okHttp库的android native client发出相同的请求,则一切正常。 Do i miss something? 我想念什么吗?

Ok so after many many of combinations i solved it, for some reason only after i called JSON.stringify(dataToSend) and added contentType: "application/json;charset=utf-8" to the request i successfully was able to receive data at the server. 好的,所以在解决了许多组合之后,由于某种原因,只有在我调用JSON.stringify(dataToSend)并将contentType: "application/json;charset=utf-8"到请求后,我才能够成功接收数据服务器。 Still it is not clear to me why need to stringify the data. 我仍然不清楚为什么需要对数据进行stringify处理。

full client code: 完整的客户代码:

$(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);
        }
      })
    }
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM