使用 nginx 在 Linux 机器上部署 Flask 和 React 应用程序时出现 cors 错误

问题描述 投票:0回答:2

我用 Flask 作为后端,React js 作为前端开发了这个应用程序。 我的文件夹结构:

mydomain/
    /server
        __init__.py
        ...
    /client (react)
        /dist
            index.html
            /assets (contains js and css)
    /venv

我的 nginx 配置:

 server {
        server_name <mydomain> www.<mydomain>;
        root /home/sabbir/<mydomain>/client/dist/;
        index index.html;

        location / {
                try_files $uri $uri/ =404;
        }
    location /api {
            include proxy_params;
            proxy_pass http://localhost:5000;
    }


    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/<mydomain>/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/<mydomain>/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot




}
server {
    if ($host = www.<mydomain>) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

当我尝试注册用户时出现此错误: 同源策略不允许读取 http://localhost:5000/auth/login 处的远程资源。 (原因:CORS请求未成功)。状态码:(空)

任何帮助将不胜感激。

reactjs nginx flask cors
2个回答
1
投票

您可以尝试安装flask-cors:

pip install flask-cors
,然后将其应用到您的应用程序上,如下所示:

from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

0
投票
def handle_cors(blueprint, auth=False):

if auth == False:
    @blueprint.after_request 
    def after_request(response):
        header = response.headers
        header['Access-Control-Allow-Origin'] = cors_origin
        header['Access-Control-Allow-Headers']='*'
        header['Access-Control-Allow-Methods']='*'
        # header['Access-Control-Allow-Credentials'] = 'true'
        # Other headers can be added here if needed
        return response
else:
    @blueprint.after_request 
    def after_request(response):
        header = response.headers
        header['Access-Control-Allow-Origin'] = cors_origin
        header['Access-Control-Allow-Headers']='*'
        header['Access-Control-Allow-Methods']='*'
        header['Access-Control-Allow-Credentials'] = 'true'
        return response
© www.soinside.com 2019 - 2024. All rights reserved.