【发布时间】:2017-01-14 19:13:15
【问题描述】:
我在 node.js 服务器上的 5000 端口上设置了 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 配置良好,我缺少什么?
编辑:就我而言,我能找到的最佳解决方案是从服务器发送页面:
app.use(express.static('web'))
app.get("/", function(req, res) {
res.sendFile(__dirname + '/web/HTML/index.html');
});
【问题讨论】:
-
@PraveenKumar 这个问题不是这个问题的重复:stackoverflow.com/questions/7969265。公认的答案是让 CORS 能够防止跨域策略出现问题,我就是这样做的。请尽量不要太快标记为重复。
-
重新打开它。看起来NodeJS的东西有问题......让我们看看NodeJS的人是否回答它。
-
非常感谢
-
您所说的“在从我的硬盘打开的静态网页中”是否意味着该文件是使用
file://协议加载的? -
@Philip 绝对
标签: jquery ajax node.js post cors