POST AJAX请求被拒绝 - CORS?

Mag*_*gix 10 ajax jquery post node.js cors

我在端口5000上的node.js服务器上设置了CORS,如下所示:

var app = express();

app.use(cors()); //normal CORS
app.options('*', cors()); //preflight 

app.post('/connect', function(req, res) { 
    console.log("Connection request received !")
});

var port = 5000;
app.listen(port, function () {
    console.log('Listening on port '+port);
});
Run Code Online (Sandbox Code Playgroud)

我现在正试图在我的硬盘打开的静态网页中使用JQuery发送AJAX POST请求:

var xhr = $.post({
            url: 'http://localhost:5000/connect',
            complete: function() {
                console.log("done !")
            },
            crossDomain: true
        });

xhr.fail(function(xhr, status, error){
    alert(error)
})
Run Code Online (Sandbox Code Playgroud)

complete永远不会调用该函数,我得到的唯一警报是来自XHR fail处理程序的警报,包含以下错误:

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
Run Code Online (Sandbox Code Playgroud)

我认为CORS配置得很好,我错过了什么?


编辑:对于我的情况,我能找到的最佳解决方案是从服务器发送页面:

app.use(express.static('web'))

app.get("/", function(req, res) {
    res.sendFile(__dirname + '/web/HTML/index.html');
});
Run Code Online (Sandbox Code Playgroud)

fri*_*evb 5

这是我正在使用的代码。它位于我的 app.js 文件中

app.all("/*", function (req, res, next) {

  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Credentials",true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Accept,X-Access-Token,X-Key,Authorization,X-Requested-With,Origin,Access-Control-Allow-Origin,Access-Control-Allow-Credentials');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});
Run Code Online (Sandbox Code Playgroud)

  • `if ( req.method === 'OPTIONS')` 救了我。谢谢!! (2认同)