POST AJAX请求被拒绝 - CORS?

时间:2016-09-07 07:45:52

标签: jquery ajax node.js post 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)
})

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

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

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

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

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

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

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

我从未使用过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();
})

这应该有用。

答案 2 :(得分:0)

我有一个使用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 
});

答案 3 :(得分:0)

CORS无法使用file协议,因为那里没有服务器可以发送回必需的标头。您使用服务器的解决方案是让CORS工作的唯一方法。