我正在构建一个使用Node.js / Express作为后端的Web应用程序。
在我的前端,我通过看起来像这样的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 :(得分:0)
尝试这样发送
xhttp.send("foo=bar&lorem=ipsum");
答案 1 :(得分:0)
尝试将标头设置为您的AJAX请求
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
然后你就可以阅读req.body
了