【问题标题】:Getting an error on my app.post() in Express.js and Node.js在 Express.js 和 Node.js 中我的 app.post() 出现错误
【发布时间】:2013-07-10 19:54:42
【问题描述】:

我在 Node.js/Express.js 中有以下代码

// Post a comment
app.post('/:id/comment', function(req, res){
    var snipp_id = req.params.id;
    var comment = req.body.comment;
    var line_num = req.body.line;

    models.Snipp.findById(snipp_id, function(err, snipp){
        snipp.comments.push({body: comment,line: line_num});
        res.send('OK');
        snipp.save();
    });
});

当我做 cURL 时:curl -X POST -H '{"comment":"test", "line":2}' http://localhost:3000/51dd25a56416c53f66000002/comment

我收到此错误:

SyntaxError: Unexpected token t
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/express/node_modules/connect/lib/middleware/json.js:76:27)
    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at _stream_readable.js:910:16
    at process._tickCallback (node.js:415:13)

我做错了什么?! :)

谢谢!

【问题讨论】:

    标签: javascript node.js express mongoose


    【解决方案1】:

    在你的 curl 命令中设置 --header "Content-Type:application/json" 并使用-d 标志发送数据

    因此:

    curl -X POST -H "Content-Type:application/json" -d '{"comment":"test", "line":2}' http://localhost:3000/51dd25a56416c53f66000002/comment
    

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 2021-05-04
      • 2017-09-25
      • 1970-01-01
      • 2016-06-24
      • 2022-09-29
      • 2018-12-12
      • 2021-09-17
      • 1970-01-01
      相关资源
      最近更新 更多