[英]Condition CORS Access-Control-Allow-Origin in Express.js
[英]Express.js GET Requests, Unable To Allow CORS
我有一个带有一些 cors 允许原始代码的 express.js 服务器:
var express = require('express');
var app = express();
var router = express.Router();
require('dotenv').config()
const bodyParser = require('body-parser')
const cors = require("cors");
const corsOptions = {
origin: '*',
credentials: true,
optionSuccessStatus: 200,
}
var allowedOrigins = ['http://localhost:4200',
'http://yourapp.com'];
app.use(cors({
origin: function(origin, callback){
// allow requests with no origin
// (like mobile apps or curl requests)
if(!origin)
return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
router.use(cors(corsOptions))
// router.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
// router.use(bodyParser.json())
router.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
router.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.get('/p', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
然后我调用一个post请求。 有用!!
this.http.post<any>('http://localhost:3000/stuff', {
dataToSend: docToStore
}).subscribe({
next: async data => {
console.log('got some data back! ', data);
},
error: error => {
}
})
但是,当我尝试调用任何 GET 请求时...出现 cors 错误。 卧槽??? 谁能解释一下这个??
this.http.get<any>('http://localhost:3000/p', {
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*' }
}).subscribe({
next: async data => {
console.error('ok ', data);
},
error: error => {
console.error('There was an error ', error);
}
})
我完全不知所措。 这完全没有意义......
Access-Control-Allow-*
标头不属于 GET(或 POST)请求,它们出现在响应中。 意外的Access-Control-Allow-Origin
标头可能是您的 GET 请求导致 CORS 错误的原因。
您的代码中有三个影响 CORS 的地方:
app.use(cors(...))
router.use(cors(...))
router.use(function(...))
直接设置Access-Control-Allow-*
标头。您应该只使用这些(最好是第一个或第二个)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.