尝试在站点上调用POST时,控制台出现以下错误。 (带角度的前端和Express后端都在Docker容器内)。
从原点“ https // frontend.mysite.com”对“ https://exp.mysite.com/i_l”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否“访问控制” -Allow-Origin标头出现在请求的资源上。
请注意,我在本地PC上的设置完全相同,并且一切正常。
下面是在快递侧配置我的server.js文件以用于CORS:
const path = require('path');
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const bodyParser = require('body-parser')
const app = express();
const router = express.Router();
const DIR = './uploads';
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname));
}
});
let upload = multer({ storage: storage });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
next();
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, function () {
console.log('Node.js server is running on port ' + PORT);
});
答案 0 :(得分:1)
在Express服务器上启用CORS的更好方法是使用 cors
尝试一下。首先:
npm install cors --save
然后:
...
const cors = require('cors')
const app = express();
...
app.use(cors());
...
答案 1 :(得分:0)
如果要使用Access-Control-Allow-Credentials,通配符*无效。您需要返回特定的起源:
res.setHeader("Access-Control-Allow-Origin", "https//frontend.mysite.com");