AJAX Post请求 - 将json对象发送到node.js服务器

时间:2018-03-21 11:39:43

标签: node.js ajax

我正在发出Ajax Post请求:

$.ajax({
        type:"POST",
        dataType:"json",
        contentType: "application/json",
        data:newWorkLog,
        url:"/add",
      })
        .done(function(response){
          console.log("Response of update: ",response)
        })
        .fail(function(xhr, textStatus, errorThrown){
          console.log("ERROR: ",xhr.responseText)
          return xhr.responseText;
        });

并期望通过我的node.js服务器将该newWorkLog对象传递给API方法:

var bodyParser = require('body-parser');
app.use(bodyParser.json())

app.post('/add', function(req, res){
        console.log(req.body) //This doesnt output anything
        res.send(JSON.stringify(req.body));
    });

在尝试了一些方法后,我决定只检查发送到我服务器的内容。

这样做,我得到的信息是:

SyntaxError: Unexpected token # in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (C:\working\app\node_modules\body-parser\lib\types\json.js:157:10)
    at parse (C:\working\app\node_modules\body-parser\lib\types\json.js:83:15)
    at C:\working\app\node_modules\body-parser\lib\read.js:121:18
    at invokeCallback (C:\working\app\node_modules\raw-body\index.js:224:16)
    at done (C:\working\app\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (C:\working\app\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:1055:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

当我调试我的newWorkLog对象时,我可以从客户端看到正确的json对象。

当我检查控制台上的参数时,我看到请求有效负载,它看起来像:

user%5Bid%5D=109&user%5BuserName%5D=myname

可能导致该错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

您说newWorkLog是一个对象,因此您需要将其转换为json以在请求中发送它。

$.ajax({
    type:"POST",
    dataType:"json",
    contentType: "application/json",
    data:JSON.stringify(newWorkLog),
    url:"/add",
})
.done(function(response){
      console.log("Response of update: ",response)
})
.fail(function(xhr, textStatus, errorThrown){
      console.log("ERROR: ",xhr.responseText)
      return xhr.responseText;
});