我的应用程序出现了CORS问题。
我的堆栈是带有Express 4和AngularJS的Node.js
我已经尝试了一些东西,但我一直在寻找所有POST / PUT请求:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
在服务器端,我使用npm cors
模块
var cors = require('cors');
var corsOptions = {
origin: [
'http://www.localhost:5555',
'http://www.somedomain.com'
],
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'Content-Length',
'Content-Range',
'Content-Disposition',
'Content-Description',
'Access-Control-Allow-Origin',
'Access-Control-Allow-Headers',
'Authorization',
'Origin',
'X-Requested-With',
'X-AUTH-TOKEN'
],
credentials: true
};
app.use(cors(corsOptions));
在AngularJS部分,我使用的是:
// App Config
App.config(['$httpProvider',
function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
]);
// Request in the Angular service
var deferred = $q.defer();
var host = 'http://www.localhost:5555';
var id = 'some-id';
var data = {};
$http.put(host + '/roles/' + id, data).
success(function (data) {
deferred.resolve(data);
}).
error(function (err) {
deferred.reject(err);
});
return deferred.promise;
GET请求正常工作。 PUT / POST请求继续返回上面的相同错误。然而,预检OPTIONS很成功。
由于
答案 0 :(得分:-1)
这适用于Express 4服务器中的CORs
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "OPTIONS, POST, GET, PUT, DELETE");
res.header("Access-Control-Allow-Headers", YOUR HEADERS HERE);
res.header('Access-Control-Allow-Credentials', true);
if ('OPTIONS' == req.method) {
return res.sendStatus(200);
} else {
next();
}
});