简体   繁体   English

无法让 React 和 Flask-CORS 在本地工作

[英]Can't get React and Flask-CORS to work locally

I'm trying to get an application with a React/NodeJS frontend and a Flask backend to run locally for development purposes.我试图让一个带有 React/NodeJS 前端和 Flask 后端的应用程序在本地运行以用于开发目的。 I've been scouring StackOverflow for the last hour, but I can't seem to get past the CORS-issue.过去一个小时我一直在搜索 StackOverflow,但我似乎无法解决 CORS 问题。 I have:我有:

import json
 
from flask import Flask, request
from flask_cors import CORS, cross_origin

app = Flask(__name__)

# Enable cors requests
CORS(app)

# Initiate model

@app.route("/query", methods=["POST"])
@cross_origin(origin="*", headers=["Content-Type"])
def query():
    """Endpoint for receiving bot response"""
    print(request)
    query = request.json
    bot_answer = blablagetanswer() ... #filling the json 
    return json.dumps({"botResponse": bot_answer})


if __name__ == "__main__":
    app.run(
        host="0.0.0.0", port=80, debug=True,
    )

I have read multiple answers, and tried many variations of CORS handling in Flask (tried with and without the @cross_origin() decorater, added @cross_origin(origin="*") or even @cross_origin(origin="*", headers=["Content-Type"]) right under the @app.route() ), but to no avail.我已经阅读了多个答案,并在 Flask 中尝试了 CORS 处理的多种变体(尝试使用和不使用@cross_origin()装饰器,添加了@cross_origin(origin="*")甚至@cross_origin(origin="*", headers=["Content-Type"])就在@app.route()下),但无济于事。

I even tried adding these two lines to my flask app:我什至尝试将这两行添加到我的 flask 应用程序中:

app.config["CORS_HEADERS"] = "Content-Type"
CORS(app, resources={r"/*": {"origins": "*"}})

It also didn't help.它也没有帮助。

I'm fetch ing from React like this:我像这样从 React fetch

var jsonData = { "lastConversations": [this.state.chatInput] }
console.log("Sending Chat: " + JSON.stringify(jsonData, null, 2));
fetch('http://my-ip:80/query', {
  method: 'POST',
  mode: 'cors',
  body: JSON.stringify(jsonData)
})

and the log does contain the text I want to send, but Chrome just says:并且日志确实包含我要发送的文本,但 Chrome 只是说:

Access to fetch at 'http://my-ip/query' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 政策阻止了从来源“http://localhost:3000”获取“http://my-ip/query”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”header . If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

What am I missing?我错过了什么? This is just for local testing, how can I get it to work?这只是为了本地测试,我怎样才能让它工作?

Turns out when working with JSON, it's important to make sure you let the other side know that you're sending application/json data.事实证明,在使用 JSON 时,确保让对方知道您正在发送应用程序/json 数据很重要。 Modifying the fetch like this solved it:像这样修改获取解决了它:

var jsonData = { "lastConversations": [this.state.chatInput] }

console.log("Sending Chat: " + JSON.stringify(jsonData, null, 2));
fetch('http://my-ip:80/query', {
  method: 'POST',
  mode: 'cors',
  headers: {   # this is the key part
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(jsonData)

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM