[英]AngularJS & Node.js CORS not working for PUT/POST
我的應用存在CORS問題。
我的堆棧是帶有Express 4和AngularJS的Node.js
我已經嘗試了一些方法,但是我不斷獲得所有POST / PUT請求:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
在服務器端,我已經使用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));
在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請求繼續返回上面的相同錯誤。 但是,預檢選項成功。
謝謝
這適用於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.