[英]jQuery + node.js express POST request
我正在嘗試向節點服務器發送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)
})
這是有效的,但我不確定使用post獲取查詢字符串中的數據是正確的方法。
我嘗試在$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',
})
將數據發布到服務器時,數據通常是urlencoded並添加到請求的正文中。 在您的示例中,它看起來像這樣:
id=<userid>&message=<message>
因此,你需要能夠解析的bodyparser.urlencoded()
是bodyparser.urlencoded()
app.use(bodyParser.urlencoded())
請注意,它並不總是urlencoded,它取決於您用來發送帖子的內容。 例如,AngularJS默認將其作為json發送。 好消息是你可以簡單地添加兩個bodyparser並且你的路由不需要知道使用了哪種方法,因為在這兩種情況下數據最終都會出現在具有鍵/值對的req.body上。
您應該閱讀快速文檔。 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)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.