从客户端,我无法解决这个问题。
在Node.js和Express.js方面,您可以使用cors模块来处理它。
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cors = require('cors');
var port = 3000;
var ip = '127.0.0.1';
app.use('*/myapi',
cors(), // With this row OPTIONS has handled
bodyParser.text({type: 'text/*'}),
function(req, res, next) {
console.log('\n.----------------' + req.method + '------------------------');
console.log('| prot:' + req.protocol);
console.log('| host:' + req.get('host'));
console.log('| URL:' + req.originalUrl);
console.log('| body:', req.body);
//console.log('| req:', req);
console.log('.----------------' + req.method + '------------------------');
next();
});
app.listen(port, ip, function() {
console.log('Listening to port: ' + port);
});
console.log(('dir:' + __dirname));
console.log('The server is up and running at http://' + ip + ':' + port + '/');
如果没有 cors(),这些 OPTIONS 必须出现在 POST 之前。
.----------------OPTIONS------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: {}
.----------------OPTIONS------------------------
.----------------POST------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: <SOAP-ENV:Envelope .. P-ENV:Envelope>
.----------------POST------------------------
阿贾克斯调用:
$.ajax({
type: 'POST',
contentType: "text/xml; charset=utf-8",
//These does not work
//beforeSend: function(request) {
// request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
// request.setRequestHeader('Accept', 'application/vnd.realtime247.sct-giro-v1+cms');
// request.setRequestHeader('Access-Control-Allow-Origin', '*');
// request.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET');
// request.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type');
//},
//headers: {
// 'Content-Type': 'text/xml; charset=utf-8',
// 'Accept': 'application/vnd.realtime247.sct-giro-v1+cms',
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'POST, GET',
// 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type'
//},
url: 'http://localhost:3000/myapi',
data: '<SOAP-ENV:Envelope .. P-ENV:Envelope>',
success: function(data) {
console.log(data.documentElement.innerHTML);
},
error: function(jqXHR, textStatus, err) {
console.log(jqXHR, '\n', textStatus, '\n', err)
}
});