CORS 配置 Flask、Angular 和 NGINX
Posted
技术标签:
【中文标题】CORS 配置 Flask、Angular 和 NGINX【英文标题】:CORS Configuration Flask, Angular and NGINX 【发布时间】:2020-12-09 05:35:00 【问题描述】:我正在尝试使用 nginx 将 Angular 应用程序上传到数字海洋水滴。这个应用程序使用烧瓶中的 API。在本地一切正常,但在 VPS 上无法正常工作。它说的是Cross-origin request blocked: Same origin policy does not allow reading of remote resources at http://127.0.0.1:5001/api/talk/
这是我的 nginx 配置:
server
server_name x.domain.com;
location /
proxy_pass http://127.0.0.1:4200;
proxy_set_header Host x.domain.com;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
add_header "Access-Control-Allow-Origin" "*";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
server
location /
proxy_pass http://127.0.0.1:5001;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
add_header "Access-Control-Allow-Origin" "*";
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
location /api/talk/
proxy_pass http://127.0.0.1:5001;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
location /api/response/
proxy_pass http://127.0.0.1:5001;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Origin "";
这是我的烧瓶配置:
app = Flask(__name__)
cors = CORS(app, resources=r"/api/*": "origins": "*")
chat = Chat()
@app.route('/api/talk/', methods=['POST'])
@cross_origin(origin='localhost')
def index():
print(request.data.decode("utf-8"))
chat.send_message(request.data)
return request.data
@app.route('/api/response/', methods=['GET'])
@cross_origin(origin='localhost')
def get():
response = chat.response
return response
def options(self):
return 'Allow': 'POST', 200, \
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST,GET'
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5001, debug=True)
而 Angular 在这里使用了烧瓶 API:
export class Message
constructor(public content: string, public sentBy: string)
@Injectable(
providedIn: "root",
)
export class MessageService
conversation = new BehaviorSubject<Message[]>([]);
readonly SERVER_URL = "http://127.0.0.1:5001";
public httpClient = axios.create();
constructor()
update(msg: Message)
this.conversation.next([msg]);
converse(msg: string)
const userMessage = new Message(msg, 'user');
this.update(userMessage);
this.sendMessage(userMessage.content)
sendMessage(msg: string)
console.log(msg)
const config =
headers:
'Content-Type': 'text/plain',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET POST',
'Access-Control-Allow-Origin': '*'
,
;
this.httpClient.post(this.SERVER_URL+'/api/talk/', btoa(msg), config)
.then(function (response)
)
.catch(function (error)
console.log(error);
);
async getResponse()
await this.delay(900);
let msg = ''
return this.httpClient.get(this.SERVER_URL+'/api/response/')
.then(response =>
msg = response.data
const botMessage = new Message(msg, 'chucho');
this.update(botMessage);
return msg
)
.catch(function (error)
console.log(error);
);
delay(ms: number)
return new Promise( resolve => setTimeout(resolve, ms) );
我的 Angular 应用在 4200 端口上运行,而 Flask API 在 5001 端口上。
希望你能帮助我。
【问题讨论】:
您的 Angular 设置为SERVER_URL = "http://127.0.0.1:5001";
- 如果在部署时仍然如此,那么它将尝试与仍在本地运行的实例对话,这将破坏 CORS。您能否根据当前窗口位置定义 SERVER_URL,但使用 5001 端口?
它正在工作!谢谢
【参考方案1】:
尝试像这样启用 CORS -
但首先通过运行安装最新的flask-cors -
pip install -U flask-cors
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app) # This will enable CORS for all routes
@app.route("/")
@cross_origin()
def helloWorld():
return "Helloworld!"
【讨论】:
以上是关于CORS 配置 Flask、Angular 和 NGINX的主要内容,如果未能解决你的问题,请参考以下文章
Go Restful API:CORS 配置适用于 React 但不适用于 Angular