Flask / React / Nginx / Dockerfile - проблема CORS - PullRequest
0 голосов
/ 01 августа 2020

Я пытаюсь использовать Nginx в качестве обратного прокси для развертывания Flask бэкэнда и React. js интерфейса на Heroku только с одним динамометрическим интерфейсом. Все работает нормально, когда я использую flask и реагирую. js встроенные серверы, но я не могу заставить его правильно работать с Nginx ни на локальном компьютере, ни на Heroku.

Flask код

from flask import Flask, request
from flask_cors import CORS
from flask_restful import Api, Resource
import time

# ------------------------------------------------------------------------------
# Flask app config + CORS
# ------------------------------------------------------------------------------
DEBUG = True

app = Flask(__name__)
app.config.from_object(__name__)

# accept CORS from frontend app
API_CORS_ORIGINS = [
    "http://localhost:8080",
]
CORS(app, origins=API_CORS_ORIGINS, supports_credentials=True)

# ------------------------------------------------------------------------------
# RESTFUL API
# ------------------------------------------------------------------------------
API_PREFIX = '/api'
api = Api(prefix=API_PREFIX)


class AuthenticationAPI(Resource):
    def get(self):
        return {'res': 'get'}, 200

    def post(self):
        print(request.get_json())
        return {'res': 'post'}, 200


class TimeAPI(Resource):
    def get(self):
        return {'res': time.time()}, 200


api.add_resource(AuthenticationAPI, '/auth')
api.add_resource(TimeAPI, '/time')

api.init_app(app)

Javascript код

import axios from 'axios';

const apiUrl = 'http://localhost:5000/api'

const callBackendAuth = async () => await axios({
    method: 'post',
    headers: {
        'Content-Type': 'application/json'
    },
    mode: 'cors',
    url: `${apiUrl}/auth`,
    data: {
        'username': 'user1',
        'password': 'pass1'
    }
}).then(res => {
    console.log(res)
}).catch(err => {
    console.error(err)
});

const callBackendTime = async () => axios({
    method: 'get',
    headers: {
        'Content-Type': 'application/json'
    },
    mode: 'cors',
    url: `${apiUrl}/time`
}).then(res => {
    console.log(res);
}).catch(err => {
    console.error(err)
})

Nginx конфигурация

server {
  listen 80; # $PORT;

  # ----------------------------------------------------------------------------
  # Serve the static files
  # ----------------------------------------------------------------------------
  root /usr/share/nginx/html;
  index index.html index.html;

  location / {
    try_files $uri $uri/ =404;
  }

  # https://create-react-app.dev/docs/production-build/#static-file-caching
  location /static {
    expires    1y;
    add_header Cache-Control "no-cache";
  }

  # ----------------------------------------------------------------------------
  # Allow access to backend using Nginx as reverse proxy
  # ----------------------------------------------------------------------------
  location /api {
    include             proxy_params;
    proxy_pass          http://127.0.0.1:5000;
    proxy_http_version  1.1;
    proxy_redirect      default;
    proxy_set_header    Upgrade $http_upgrade;
    proxy_set_header    Connection "upgrade";
    proxy_set_header    Host $host;
    proxy_set_header    X-Real-IP $remote_addr;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host $server_name;
  }
}

1 Ответ

0 голосов
/ 01 августа 2020

Проблема здесь в том, что прокси Nginx не передает заголовки ответа от приложения JavaScript клиенту. Вам нужно либо установить эти заголовки в конфигурации Nginx с помощью add_header Access-Control-Allow-Origin "https://url";, либо указать заголовок с помощью proxy_pass_header

...