像这样的简单Nodejs服务器
var express = require('express'), app = express();
var bodyParser = require('body-parser');
app.use(function(req, res, next){
res.header("Access-Control-Allow-Origin", "http://localhost:9877");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST");
res.header("Access-Control-Allow-Credentials", "false");
/** When Using XMLHttpRequest, set true
* XDomainRequest, set false
*/
next();
});
app.use(bodyParser.text());
app.get('/', function(req, res){
console.log("GET METHOD")
console.log(req.body)
res.send(200);
});
app.post('/e8', function(req, res){
console.log("POST METHOD")
console.log(req.body)
res.send(200);
});
app.listen(3001, function(){
console.log('CORS-enabled web server listening on port 3001');
});
服务器能够接收XMLHttpRequest请求主体,但不能接收XDomainRequest的主体。
可能导致什么问题?
两个客户端都使用文本/普通标头,如xhr.setRequestHeader('Content-Type', 'text/plain')
,而XDomainRequest只能使用text / plain,默认标头。
编辑1:添加我的客户端代码
//XDR
var xdr = new XDomainRequest();
xdr.onload = function() {
console.log("ON LOAD")
}
xdr.open('POST',url);
xdr.onprogress = function () {
console.log("ON PROGRESS")
};
xdr.timeout=2000
xdr.ontimeout = function () {
console.log("TimeOut")
};
xdr.onerror = function () {
console.log("ON ERROR")
};
xdr.send(JSON.stringify(myData));
//XHR
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 /** responseText is not available yet */) {
const statusCode = xhr.status
const responseText = xhr.responseText
//some code
}
}
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-Type', 'text/plain')
xhr.withCredentials = true
xhr.timeout = 2000
xhr.ontimeout = function (event) {
console.log("TIMEOUT")
}
xhr.send(JSON.stringify(myData))