簡體   English   中英

被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查

[英]blocked by CORS policy: Response to preflight request doesn't pass access control check

我有一個 CORS 錯誤,我嘗試了一切。 我仍然收到錯誤:

從來源“ http://www.example.com ”訪問位於“ https://myapp.herokuapp.com/api/contact ”的 XMLHttpRequest 已被 CORS 策略阻止:對飛行前請求的響應未通過訪問控制檢查: 請求的資源上不存在“Access-Control-Allow-Origin”header。

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}`);
});
**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()
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM