【问题标题】:jQuery + node.js express POST requestjQuery + node.js 表达 POST 请求
【发布时间】:2015-11-14 03:12:25
【问题描述】:

我正在尝试向节点服务器发送发布请求。 这是我的客户端代码:

function send(userid,message){
    $.ajax({
        method: "POST",
        url: "/chat/messages?id="+userid+'&message='+message
    })
    clear();
}

这是我的服务器端代码:

  app.post('/chat/messages',function (req,res){
    var query = url.parse(req.url,true).query
    insertMessage(query.id,query.message)
  })

这可行,但是我不确定使用 post 在查询字符串中获取数据是否正确。

我尝试在$ajax参数中添加一个数据字段:

function send(userid,message){
    $.ajax({
        method: "POST",
        url: "/chat/messages"
        data : {'id' : userid, 'message' : message}
    })
    clear();
}

并在服务端使用bodyParser()解析body内容:

app.use(bodyParser.json())
app.post('/chat/messages',function (req,res){
    console.log(req.body)
})

但是当我记录响应时,body{ } 对象始终为空。 这是为什么? POST 请求是否需要 <form> 标签?

我尝试编辑我的 ajax 请求以使用 json 作为 dataType 并对数据进行字符串化,但 req.body 仍然为空。

$.ajax({
    method: "POST",
    url: "/chat/messages",
    data : JSON.stringify({'id' : userid, 'message' : message}),
    dataType: 'json',
})

【问题讨论】:

  • 你没有发送 json,所以......那是错误的 bodyparser。如果要发送 json,则需要将要发送的对象字符串化到 data 参数。在这种情况下也有助于设置 contentType。
  • 但即使使用bodyParser.raw(),请求正文仍然为空。
  • urlencoded 是你想要的。
  • 是的! urlencoded 作品!谢谢凯文 B!
  • urlencoded 有效,因为 POST 字段在正文中作为 urlencoded 字符串发送,很像在 GET 请求的 url 中发送的查询字符串。

标签: javascript jquery ajax node.js


【解决方案1】:

当您将数据发布到服务器时,通常会对数据进行 urlencoded 并添加到请求的正文中。在您的示例中,它看起来像这样:

id=<userid>&message=<message>

因此,您需要能够解析的bodyparser是bodyparser.urlencoded()

app.use(bodyParser.urlencoded())

请注意,它并不总是 urlencoded,这完全取决于您用于发送帖子的内容。例如,AngularJS 默认将其作为 json 发送。好消息是您可以简单地添加两个 bodyparsers,并且您的路由不需要知道使用了哪种方法,因为在这两种情况下,数据最终都会以键/值对出现在 req.body 上。

【讨论】:

    【解决方案2】:

    您应该阅读 express 文档。 http://expressjs.com/api.html#req

    // For regular html form data
    app.use(bodyParser.urlencoded())
    app.post('/chat/messages',function (req,res){
        console.log(req.body);
        console.log(req.query.id);
        console.log(req.query.messages);
    })
    

    你也可以做 req.params

    app.post('/chat/messages/:id',function (req,res){
        console.log(req.body);
        console.log(req.query);
        console.log(req.params.id)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 2011-09-07
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 2018-05-04
      • 1970-01-01
      相关资源
      最近更新 更多