javascript - Flask / React / Nginx / Dockerfile - CORS 问题
问题描述
我正在尝试使用 Nginx 作为反向代理在 Heroku 上部署一个 Flask 后端和一个 React.js 前端,只有一个测功机。当我使用flask和react.js内置服务器时一切正常,但我无法使其在Nginx上正常工作,无论是在本地还是在Heroku上。
烧瓶代码
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;
}
}
解决方案
这里的问题是 Nginx 代理没有将响应头从 JavaScript 应用程序传递到客户端。您要么需要在 Nginx 配置中设置这些标头,add_header Access-Control-Allow-Origin "https://url";
要么使用proxy_pass_header
推荐阅读
- node.js - Firestore 交易 node.js 查询
- apache-spark - spark从第二个表中存在但在不同列中的值填充第一个表中的列值
- regex - 正则表达式。Notepad ++如何用自身和附加符号/单词替换一行?
- tensorflow - 我们的混淆矩阵没有意义
- google-apps-script - 希望根据另一列的值在 Google 表格中将复选框值设置为 TRUE
- r - 如何使用跨多列的 if 语句编写 for 循环?
- javascript - 根据从数组中提取的值减少对象值?
- python - yfinance 下载数据时返回错误
- terraform - Terraform:从对象列表中检索值
- r - 根据 R 中的值绘制具有条件颜色的数据