POST AJAX请求被拒绝 – 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); }); 

我现在正尝试使用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) }) 

completefunction从来没有被调用,我得到的唯一警报是来自XHR fail处理程序的警报,其中包含以下错误:

 NS_ERROR_DOM_BAD_URI: Access to restricted URI denied 

我认为CORSconfiguration良好, 我错过了什么?


编辑 :对于我的情况下,我可以find最好的解决scheme是从服务器发送页面:

 app.use(express.static('web')) app.get("/", function(req, res) { res.sendFile(__dirname + '/web/HTML/index.html'); }); 

这是我正在使用的代码。 它位于我的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(); } }); 

我从来没有使用Cors(),所以我不能说那件事。 但是你可以通过设置node.js头来手动允许跨源数据共享。

在所有请求上添加此预处理

 app.route('*') .all(function(req, res, next) { res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-API-TOKEN, Content-Type, Authorization, Content-Length, X-Requested-Wit h'); next(); }) 

这应该工作。

我有一个使用cors的项目。

使用的节点代码只是:

 const cors = require('cors'); const express = require('express'); const app = express(); app.use(cors()); /* Connect/other routes here */ 

jquery代码看起来不同:

 $.post('http://localhost:5000/connect', {}).done( () => { // Request complete }).fail((jqXHR) => { // Request failed }); 

CORS不能使用file协议,因为没有服务器在那里发送必要的头文件。 使用服务器的解决scheme是获得CORS工作的唯一方法。