我用nginx1.18.0在服务器ubuntu20.04中部署了一个react应用程序,这是.conf文件。
server {
listen 80;
server_name myapp.com;
return 301 https://myapp.com$request_uri;
root /var/www/myapp/build;
index index.html;
access_log /var/log/nginx/myapp.access.log;
error_log /var/log/nginx/myapp.error.log;
location / {
try_files $uri /index.html =404;
}
}在同一台服务器上,我部署了我的FastApi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"https://myapp.com",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/')
def home():
return {'message': 'Hi app'}然后,从我的react应用程序中,我通过axios发送了一个请求:
const API = "http://127.0.0.1:8000/";
const response = await axios(API);我的api运行在http://127.0.0.1:8000中,我得到“交叉原产地请求被阻塞:相同的原产地策略不允许在http://127.0.0.1:8000上读取远程资源。(原因: CORS请求不成功)。状态代码:(null)”。
这是我在浏览器中可以看到的请求头:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-MX,es;q=0.8,en-US;q=0.5,en;q=0.3
Connection: keep-alive
Host: 127.0.0.1:8000
Origin: https://myapp.com
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:102.0) Gecko/20100101 Firefox/102.0在我的本地,我有相同的应用程序和api,我没有问题,不同的是,反应应用程序由npm在http://localhost:3000中运行,当然,在我的api中允许的来源中,我有"http://localhost:3000“
发布于 2022-06-01 05:48:01
考虑在nginx.中设置标头
编辑文件/etc/nginx/sites启用/yoursite
添加: add_header访问-控制-允许-原产地*;
如下所示:
server {
...
...
add_header Access-Control-Allow-Origin *;
...
...
}
}重新启动你的nginx。
https://stackoverflow.com/questions/72456887
复制相似问题