[英]CORS POLICY EXPRESS
I have this problem on my production server under express node.js : 我的生产服务器在express node.js下遇到此问题:
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." “对预检请求的响应未通过访问控制检查:所请求的资源上不存在'Access-Control-Allow-Origin'标头。”
But i have write that to test : 但是我已经写了测试:
const allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('access-control-allow-credentials', true);
return next();
}
app.use(allowCrossDomain)
Other example : 其他例子:
// CORS middleware
const allowCrossDomain = function(req, res, next) {
var allowedOrigins = ['http://127.0.0.1:9091', 'http://localhost:9091', 'http://localhost:9090'];
var origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.header('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,x-access-token');
res.header('access-control-allow-credentials', true);
return next();
}
app.use(allowCrossDomain)
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
router.get('/me', function(req, res) {
let token = req.headers['x-access-token'];
if (!token) return res.status(401).send({ auth: false, message: 'No token provided.' });
jwt.verify(token, config.secret, function(err, decoded) {
if (err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
res.status(200).send(decoded);
});
});
install cors
and you wont be any problems const cors = require('cors');
安装cors
,您将不会遇到任何问题const cors = require('cors');
app.use(cors());
link on npm https://www.npmjs.com/package/cors 链接到npm https://www.npmjs.com/package/cors
It sounds like likely OPTIONS
request type is being blocked from a browser based request. 听起来好像OPTIONS
请求类型已被基于浏览器的请求阻止。 Add OPTIONS
to the Access-Control-Allow-Methods
head as an allowed method: 将OPTIONS
作为Access-Control-Allow-Methods
添加到Access-Control-Allow-Methods
头中:
// CORS middleware
const allowCrossDomain = function(req, res, next) {
var allowedOrigins = ['http://127.0.0.1:9091', 'http://localhost:9091', 'http://localhost:9090'];
var origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.header('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST'); // added OPTIONS as an allowed method
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,x-access-token');
res.header('access-control-allow-credentials', true);
return next();
}
app.use(allowCrossDomain)
Hopefully that helps! 希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.