【问题标题】:blocked by CORS policy: Response to preflight request doesn't pass access control check被 CORS 策略阻止:对预检请求的响应未通过访问控制检查
【发布时间】: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


【解决方案1】:
**Try this i hope it works for you**

app.use((req,res, next)=>{
    res.header('Access-Control-Allow-Origin','*');
    res.header(
        'Access-Control-Allow-Headers','Origin ,X-Requested-With,Content-Type, Access,Authorization'
    );

    if(req.Method==='OPTIONS'){
        req.header('Access-Control-Allow-Methods','POST,PUT,PUSH,PATCH,DELETE,GET');
        return res.status(200).json({})
    }

    next()
})

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 2019-04-17
    • 2020-01-23
    • 2019-12-14
    • 1970-01-01
    • 2019-04-11
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多