如何通过 POST 将字符串从客户端发送到服务器



我想从我的节点js应用程序的前端发送到后端。

在服务器端,我的代码如下所示:

app.post('/mydb/post', function(req, res, next) {
console.log(req.body);
});

字符串应通过以下方式发送:

var http = new XMLHttpRequest();
var url = '/mydb/post';
var params = 'john';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'text/plain');
http.onload = function () {
// do something to response
console.log(this.responseText);
};
http.send(params);

但是请求的正文似乎是空的。

也许你知道一些事情,这会有所帮助。

亲切问候 毫克

你必须改变内容类型。
使用这个。

https://gist.github.com/seunggabi/6aa43dbcf4d5238d940f7b0b49fee989

function requestUtils(method, url, body) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log(this);
console.log(url, body);
}
}
xhr.send(body); 
}
requestUtils('post', '/mydb/post', 'name=john')

最新更新