【发布时间】:2020-09-30 19:46:54
【问题描述】:
我遇到了 CORS 错误,我尝试了所有方法。我仍然收到错误:
从源“http://www.example.com”访问“https://myapp.herokuapp.com/api/contact”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { contact } = require('./contact');
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); //also tried 'https://myapp.herokuapp.com'
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
next();
});
const proxyurl = 'https://myapp.herokuapp.com/';
const url = 'http://www.example.com';
fetch(proxyurl + url)
.then((response) => response.text())
.then((contents) => console.log(contents))
.catch(() => console.log('Can’t access ' + url + ' response. Blocked by browser?'));
app.post('https://myapp.herokuapp.com/api/contact', contact);
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
【问题讨论】:
-
另外,package.json 文件中是否需要
"proxy": "https://localhost:80"? -
我不确定你是否可以同时使用
app.use(cors())和app.use(/* your custom cors middleware */) -
我试过了 :(
标签: javascript node.js heroku cors