可以得到反应和烧瓶 - 在本地工作

发布于 2025-01-21 07:18:10 字数 1630 浏览 1 评论 0原文

我正在尝试使用React/nodejs前端和烧瓶后端来获取一个应用程序,以便在本地运行以进行开发目的。最后一个小时,我一直在搜寻Stackoverflow,但是我似乎无法超越CORS问题。我有:

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,
    )

我已经阅读了多个答案,并尝试了在烧瓶中进行多种cors处理的变化(在有或没有@cross_origin() decorater中,添加了@cross_origin(oneration =“*”)甚至@cross_origin(onect =“*”,headers = [“ content-type”]) @app.route()),但无济于事。

我什至尝试在烧瓶应用程序中添加这两行:

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

也无济于事。

fetch from react这样:

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)
})

日志确实包含我要发送的文本,但是Chrome只是说:

访问'http:// my-ip/query''http:// localhost:3000'已被CORS策略阻止:no'access-control-control-allow-origin'标头请求的资源。如果不透明的响应满足您的需求,请将请求模式设置为“无库”,以通过禁用CORS来获取资源。

我想念什么?这只是用于本地测试,我该如何工作?

I'm trying to get an application with a React/NodeJS frontend and a Flask backend to run locally for development purposes. I've been scouring StackOverflow for the last hour, but I can't seem to get past the CORS-issue. 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.

I even tried adding these two lines to my flask app:

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

It also didn't help.

I'm fetching from React like this:

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:

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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What am I missing? This is just for local testing, how can I get it to work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

征﹌骨岁月お 2025-01-28 07:18:10

事实证明,在与JSON合作时,重要的是要确保您让对方知道您正在发送应用程序/JSON数据。像这样修改获取解决方案:

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)

})

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. 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)

})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文