我正在尝试使用 NodeJS/Express 构建一个服务(驻留在与调用它的站点不同的子域上)。
我的 GET 和 POST 方法工作正常,但我在使用 PUT 时遇到了一些问题。
我尝试实现corser,但仍然收到以下错误:
XMLHttpRequest cannot load http://services.example.org/jobs/_id/5503bb957e4eacd821b5c046. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.org' is therefore not allowed access.
下面是我的corser实现。我知道其中一些可能是多余或不必要的。我只是想找到使 PUT 请求成功完成的神奇设置。
app.use(corser.create({
simpleRequestHeaders: corser.simpleRequestHeaders.concat(["PUT"]),
simpleRequestHeaders: corser.simpleRequestHeaders.concat(["OPTIONS"]),
simpleResponseHeaders: corser.simpleResponseHeaders.concat(["PUT"]),
simpleResponseHeaders: corser.simpleResponseHeaders.concat(["OPTIONS"]),
requestHeaders: corser.simpleRequestHeaders.concat(["X-Requested-With"])
}));
app.all('*', function(request, response, next) {
response.header('Access-Control-Allow-Origin', '*');
response.header('Access-Control-Allow-Headers', 'X-Requested-With');
response.header('Access-Control-Allow-Headers', 'Content-Type');
response.header('Access-Control-Allow-Methods', 'GET');
response.header('Access-Control-Allow-Methods', 'POST');
response.header('Access-Control-Allow-Methods', 'PUT');
response.header('Access-Control-Allow-Methods', 'DELETE');
response.header('Access-Control-Allow-Methods', 'OPTIONS');
next();
});
最佳答案
我联系了 corser 的首席开发人员,发现他们非常有帮助。
这是让我解决 CORS 问题的 Elixir 。
var corser = require('corser');
<小时/>
// Configure CORS (Cross-Origin Resource Sharing) Headers
app.use(corser.create({
methods: corser.simpleMethods.concat(["PUT"]),
requestHeaders: corser.simpleRequestHeaders.concat(["X-Requested-With"])
}));
app.all('*', function(request, response, next) {
response.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With,Authorization,Access-Control-Allow-Origin');
response.header('Access-Control-Allow-Methods', 'POST,GET,DELETE');
response.header('Access-Control-Allow-Origin', '*');
next();
});
希望这对将来遇到类似问题的任何人都有用。
关于node.js - NodeJS/Express PUT 请求失败并显示 : No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29069835/