[英]AngularJS & Node.js CORS not working for PUT/POST
I have a CORS problem with my app. 我的应用存在CORS问题。
My stack is Node.js with Express 4 and AngularJS 我的堆栈是带有Express 4和AngularJS的Node.js
I already have tried a few things but I keep getting for all POST/PUT requests: 我已经尝试了一些方法,但是我不断获得所有POST / PUT请求:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
In the server side I have enabled CORS using the npm cors
module 在服务器端,我已经使用npm cors
模块启用了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));
In the AngularJS part I am using this: 在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;
The GET requests work fine. GET请求工作正常。 The PUT/POST requests keep returning the same error above. PUT / POST请求继续返回上面的相同错误。 The preflight OPTIONS is successful however. 但是,预检选项成功。
Thanks 谢谢
This works for me with CORs in an Express 4 server 这适用于Express 4服务器中的COR
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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.