2015-11-13 576 views
1

我试图向一个节点服务器发送一个post请求。 这是我的客户端代码:jQuery + node.js表示POST请求

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

这工作,但我不知道使用后得到的查询字符串中的数据是正确的要走的路。

我试图在$ajax参数添加数据字段:

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

而在服务器端使用bodyParser()解析体内容:

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', 
}) 
+0

你不发送JSON,所以...这是错误的bodyparser。如果您想发送json,则需要将发送给数据参数的对象串联起来。在这种情况下,也可以帮助设置contentType。 –

+0

,但即使使用'bodyParser.raw()',请求主体仍为空。 –

+0

为什么我的问题被低估?有人能告诉我它有什么问题吗? –

回答

2

当您将数据发布到服务器时,数据通常被urlencoded并添加到请求的主体中。在你的榜样,它应该是这样的:

id=<userid>&message=<message> 

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

app.use(bodyParser.urlencoded()) 

注意,它并不总是url编码,这一切都取决于关于你用来发送帖子的内容。例如,AngularJS默认将其作为json发送。好消息是,您可以简单地添加bodyparsers,而且您的路由不需要知道使用哪种方法,因为在这两种情况下,数据都会以包含键/值对的req.body结尾。

1

您应该阅读快递文档。 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) 
})