React 和 Express 阻止了跨域请求

IT技术 javascript node.js reactjs cors
2021-05-09 17:49:00

所以当我尝试使用 React 将数据发送到后端时,我遇到了这个错误。据我所知,我需要允许在后端和.htaccess文件中进行通信。以下是我使用的一些链接:

没有 'Access-Control-Allow-Origin' - 节点/Apache 端口问题

Access-Control-Allow-Origin 标头如何工作?

他们都有代码,但没有帮助。

到目前为止,我的服务器端代码是这样的:

app.use(function (req, res, next) {
    // Website you wish to allow to connect
    // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'POST');

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

这是我的客户端代码:

sendMail(e) {
    e.preventDefault();
    var name = document.getElementById('name').value;
    var contactReason = document.getElementById('contactReason').value;
    var email = document.getElementById('email').value;
    var additionalInfo = document.getElementById('additionalInfo').value;
    var body = {
        name: name,
        contactReason: contactReason,
        email: email,
        additionalInfo: additionalInfo,
    };
    console.log(JSON.stringify(body));
    fetch('http://localhost:4000/', {
        method: 'POST',
        body: body,
    }).then(r => console.log(r)).catch(e => console.log(e));
}

那么我错过了什么?我没有.htaccess文件,但我都是在本地完成的,所以我不确定我是否可以使用它。

在我看来,我允许我所需要的一切,但我想这还不够。

如果您要标记为重复,请至少确保我的问题包含在答案中。

4个回答

有一个名为 cors 的节点包,这使它非常容易。

$npm install cors

const cors = require('cors')

app.use(cors())

你不需要任何配置来允许所有。

有关更多信息,请参阅 Github 存储库:https : //github.com/expressjs/cors

一个原因可能是您将路由用作 localhost:8000 而不是 http://localhost:8000。

利用

http://localhost:8000

不要使用

localhost:8000

如果你添加这个标题

res.setHeader('Access-Control-Allow-Origin', '*');

您正在使用凭证模式(意味着您正在从您的应用程序发送一些身份验证 cookie)并且对于 CORS 规范,您不能在此模式下使用通配符 *。

您应该更改Access-Control-Allow-Origin标头以匹配生成请求的特定主机

你可以改变这一行:

res.header('Access-Control-Allow-Origin', '*');

res.header('Access-Control-Allow-Origin', 'the ip address');

但为了更通用,这样的事情应该有效:

res.setHeader('Access-Control-Allow-Origin', req.header('origin') 
|| req.header('x-forwarded-host') || req.header('referer') || req.header('host'));

此外,您甚至必须允许来自浏览器的 OPTIONS 请求,否则您将收到预检请求错误。

res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');

给任何人,这可能会有帮助,我用axioswithCredentials: true

在我的 Express 后端,我只是在做,

app.use(cors())

修复它的方法是withCredentials: true从 React 前端删除或将我的后端更改为,

app.use(cors({ credentials: true }))