我正在尝试通过 XML POST 请求将数据发送到 Node.js 服务器并读取数据并将适当的响应发送回客户端?但是,我一直无法访问 request.body 值?代码有问题吗?
我已经尝试了请求数据的各种控制台日志,但找不到它?
HTML 客户端
var xhr = new XMLHttpRequest();
xhr.open("POST", '/view/translation', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
console.log(xhr.responseText)
}
}
xhr.send("data= 'kdjkkafjdkajs'");
// xhr.send(new Int8Array());
// xhr.send(document);
节点.JS服务器端
var fs = require('fs');
var express = require('express');
var app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true, type: 'application/x-www-form-urlencoded' }));
router.post('/translation', (request, response) => {
const data = request.body; //<---
console.log(data)
response.json('Hello'+ data);//<--
})
控制台.log(data( 在服务器端返回 -->{} 浏览器返回 --> ---> [对象对象]
编辑
所以回顾一下这个"xhr.send("data= 'kdjkkafjdkajs'"(;"这不是您编写 XML 请求的方式。
这应该是:
xhr.send("data=kdjkkafjdkajs"(;
或者使用更多选项并使用变量数据:
xhr.send("uid="+usr_num+"&l="+learn(;
这随后可以在req.body.uid等中找到。
在节点中使用.js:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '20mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
好的,所以问题已经发现,我在一个模块中工作,没有意识到快递正在使用:
app.use(express.json({ limit: '1MB' }((;
对于任何传入的请求。