首页 > 解决方案 > nginx 上 Cloudflare、ExpressJS 和 ReactJS 的 CORS 错误

问题描述

通过 Cloudflare 切换到域名后,我无法克服 CORS 错误。我似乎无法让后端 api 使用像这样的域名https://www.my_domain.com/api

我做了什么:

  1. 应用 nginx 解决方案并重启 nginx
  2. 在 cloudflare 中,我使用三个 A 记录更新了 DNS 管理:*、www 和 <my_domain.com>
  3. 在 cloudflare 中始终使用 HTTPS 设置为开启
  4. ExpressJS 启用cors
location /api {
    proxy_pass http://localhost:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}


location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

sudo nginx -t && sudo systemctl restart nginx

A record, Name: *, Content: <server_ip>, TTL: Auto, Proxy status: DNS only
A record, Name: <my_domain_name>, Content: <server_ip>, TTL: Auto, Proxy status: Proxied
A record, Name: www, Content: <server_ip>, TTL: Auto, Proxy status: Proxied

当然,我已经添加了 cors 库来表达如下:

const express = require("express");
const cors = require("cors");
require('dotenv').config()

const app = express();

if (process.env.NODE_ENV === 'production') {
    app.use(cors({ origin: `${process.env.CLIENT_URL}` }));
}
NODE_ENV=production
CLIENT_URL=http://my_domain.com
CLIENT_URL=/api

我还注意到,在浏览器控制台中,它显示请求正在按预期发送,http://<server_ip>:8000/api而不是https:<domain_name>/api按预期发送。

另外,我今天刚刚更改了域名。

尽管有上述这些设置,但当我尝试登录时,我看到请求由于 cors 错误而被阻止。

什么可能导致cors错误?

标签: reactjsexpressnginxcorscloudflare

解决方案


按照本教程...

https://medium.com/@nishankjaintdk/serving-a-website-on-a-registered-domain-with-https-using-nginx-and-lets-encrypt-8d482e01a682

结果发现了这些说明......

https://certbot.eff.org/lets-encrypt/ubuntubionic-nginx

在我的 linux 终端中运行这些命令(来自 certbot 指令)......

sudo snap install core; sudo snap refresh core; sudo apt-get remove certbot; sudo snap install --classic certbot; sudo ln -s /snap/bin/certbot /usr/bin/certbot; sudo certbot --nginx

此时出现了域名提示。所以,我像这样输入了我的域...

my_domain.com www.my_domain.com

根据说明,然后我测试了续订(您需要每年续订,但这些将被放入 cron 以*希望自动续订)

sudo certbot renew --dry-run

域 api 工作但反应应用程序尚未显示,这表明 Cloudflare 中可能存在一些问题。

之后,我让我的网站像这样显示在浏览器中......

  1. 登录 Cloudflare.com
  2. 转到域的 SSL/TLS 加密设置
  3. 将其从灵活更改为完整
  4. 单击边缘证书
  5. 关闭 HTTPS 始终开启

在完成上述所有操作后,它导致域显示了我的反应应用程序,该应用程序完全与 api 配合使用并且没有 CORS 错误。


推荐阅读