reactjs - nginx 上 Cloudflare、ExpressJS 和 ReactJS 的 CORS 错误
问题描述
通过 Cloudflare 切换到域名后,我无法克服 CORS 错误。我似乎无法让后端 api 使用像这样的域名https://www.my_domain.com/api
我做了什么:
- 应用 nginx 解决方案并重启 nginx
- 在 cloudflare 中,我使用三个 A 记录更新了 DNS 管理:*、www 和 <my_domain.com>
- 在 cloudflare 中始终使用 HTTPS 设置为开启
- ExpressJS 启用
cors
库
- 下面应用了 nginx 解决方案... 注意:我在 3000 端口上运行了 React。React 在浏览器中访问域名时显示!
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;
}
- 我用来测试和重启 nginx 的命令:
sudo nginx -t && sudo systemctl restart nginx
- 在 cloudflare DNS 管理中...
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
在 cloudflare、SSL/TLS、Edge 证书中,始终使用 HTTPS 设置为开启。
ExpressJS 启用
cors
库
当然,我已经添加了 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}` }));
}
- 我的后端 .env 文件:
NODE_ENV=production
CLIENT_URL=http://my_domain.com
- 我的前端反应 .env 文件
CLIENT_URL=/api
我还注意到,在浏览器控制台中,它显示请求正在按预期发送,http://<server_ip>:8000/api
而不是https:<domain_name>/api
按预期发送。
另外,我今天刚刚更改了域名。
尽管有上述这些设置,但当我尝试登录时,我看到请求由于 cors 错误而被阻止。
什么可能导致cors错误?
解决方案
按照本教程...
结果发现了这些说明......
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 中可能存在一些问题。
之后,我让我的网站像这样显示在浏览器中......
- 登录 Cloudflare.com
- 转到域的 SSL/TLS 加密设置
- 将其从灵活更改为完整
- 单击边缘证书
- 关闭 HTTPS 始终开启
在完成上述所有操作后,它导致域显示了我的反应应用程序,该应用程序完全与 api 配合使用并且没有 CORS 错误。
推荐阅读
- spring - https//recipe-010-webhook.herokuapp.com?op=webhook .Error - Invalid URI: The URI scheme is not valid
- angular - angular 9 数组在订阅方法中为空
- excel - 将 Excel 值传递给同一类的多个方法
- javascript - JS倒数计时器停止在0
- firefox - 无法从 Firefox 中的 PeerConnection 检索 RTCVideoSourceStats
- hadoop - HDFS 和 ADLS 有什么区别?
- python - Python 数据操作 - pd.apply
- sql - case when 与 if else 语句
- python-3.x - 当我们需要在 exec() 函数中指定数据类型时?
- json - 在 telegraf.conf 中将 JSON 值解析为单独的字符串