gpt4 book ai didi

javascript - AngularJS 和 Node.js CORS 不适用于 PUT/POST

转载 作者:行者123 更新时间:2023-11-30 06:52:10 26 4
gpt4 key购买 nike

我的应用程序存在 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 请求不断返回上面相同的错误。然而,预检 OPTIONS 是成功的。

谢谢

最佳答案

这对我来说适用于 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();
}
});

关于javascript - AngularJS 和 Node.js CORS 不适用于 PUT/POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36717973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com