2017-02-19 72 views
1

我正在構建一個使用Node.js/Express作爲後端的Web應用程序。使用Node.js/Express訪問AJAX POST數據

在我的前端,我送通過JavaScript的AJAX請求到服務器,看起來像這的:

var xhttp = new XMLHttpRequest(); 
xhttp.open("POST", "http://localhost:8080", true); 
xhttp.send("sometexthere"); 

這正好我的Node.js服務器。到目前爲止,我已經能夠很好地迴應這些要求。但是,現在我想訪問我的服務器上的「sometexthere」。

var express = require('express') 
var app = express() 
var bodyParser = require('body-parser') 
app.use(bodyParser.urlencoded({extended: true})); 
app.use(bodyParser.json()); 

//some other stuff 

app.post('/', function(req, res) { 
     //How do I access the text sent in xhttp.send() 
} 

我試過使用req.body和req.query。但是,所有這些值都顯示爲空。如何使用xhttp.send()發送文本,然後從Express中的req對象獲取它?

謝謝!

回答

0

嘗試設置標題,您的AJAX請求

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

,那麼你將能夠在req.body閱讀

+0

謝謝!這與其他建議一起工作。 – TLF

0

試試這個發送像這樣

xhttp.send("foo=bar&lorem=ipsum"); 
+0

我怎麼那麼訪問它? req.body? – TLF