XMLHttpRequest的坑

  • 问题: 在浏览器调试发送XMLHttpRequest,send,在express服务器上的body为空

  • Creator 版本:2.4.3

  • 目标平台:vscode本地调试google浏览器

今天搞了下creator的XMLHttpRequest,发现服务器和客户端两端可以联通,但是数据交换有问题。
以下是客户端代码:
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
var response = xhr.responseText;
console.log(response);
}
};
xhr.open(“POST”, “http://127.0.0.1:7321/hotupdate”, true);
xhr.send(“id = 10”);
以下是服务器代码:
const app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.listen(RoutineInfo.webPort, function () {
console.log(‘the server is start at p’);
});
app.use(function (req, res, next) {
console.log(req.body);
console.log(ip地址是: ${req.ip});
next();
});
如果不添加 Content-Type为表单类型的,设置text或者是json类型的,express框架解析的body就是个{}空的,如果是表单倒是会解析。我也不知道为什么。主要我不是后端的,对服务器不了解。但是客户端可以接受到服务器的发的主体消息。
以下是发送的服务器代码:
res.writeHead(200, { “Content-Type”: “text/plain;charset=‘utf-8’”, ‘Access-Control-Allow-Origin’:
‘*’, ‘Access-Control-Allow-Methods’: ‘PUT,POST,GET,DELETE,OPTIONS’ });
res.write(“dddd”);
res.end();
客户端是可以接受到"dddd"返回的。
有了解为什么的吗,感觉踩了一天的坑,但不知道咋回事,

嘀嘀嘀,有人回复吗

不在本地调试后把代码放到服务器和打包安卓发现可以
客户端请求:
xhr.open(“POST”, “http://101.35.181.10:7321/hotupdate”, true);
xhr.send(“id = 10”);
服务器返回:
[Object: null prototype] { 'id ‘: ’ 10’ }
ip地址是: ::ffff:223.104.5.199。

所以结论是浏览器不行吗,有大哥解惑没