简体   繁体   English

如何使用Reactjs fetch将POST数据发送到烧瓶

[英]How to send POST data to flask using Reactjs fetch

I'm very new to react and i'm trying to get a hold on how to properly use fetch. 我很反应,我试图抓住如何正确使用fetch。 I have this python flask route I'm trying to hit from the back end which looks something like this: 我有这个python flask路线,我试图从后端击中,看起来像这样:

@app.route('/api/v1', methods=['POST'])
def postTest():
    if not request.json:
        return "not a json post"
    return "json post succeeded"

now when I hit this point with post-man I'm actually able to get my successful message. 现在当我用post-man达到这一点时,我实际上能够得到我成功的消息。

This is what my reactjs fetch looks like: 这就是我的reactjs fetch看起来像:

 returnFlaskPost() { return fetch( 'http://localhost:5000/api/v1', { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'POST', body: { 'user1':'1234' } }); } 

Whenever I run my application and attempt to read this function to the console the result I get is this: 每当我运行我的应用程序并尝试将此函数读取到控制台时,我得到的结果是:

在此输入图像描述

Could someone please explain to me what am I doing wrong and what can I do to fix this. 有人可以向我解释我做错了什么,我该怎么做才能解决这个问题。 I'd greatly appreciate it. 我非常感激。

It is a problem of Cross Origin Resource Sharing. 这是跨源资源共享的问题。 In you case you are trying to access the API endpoint from the different URL as the API is being served on itself. 在您的情况下,您正在尝试从不同的URL访问API端点,因为API正在自行提供。 By the way, 127.0.0.1:3000 and 127.0.0.1:5000 considered as two different URLs, therefore causing the error that you are referring to. 顺便说一下,127.0.0.1:3000和127.0.0.1:5000被视为两个不同的URL,因此导致您所指的错误。 So, to fix this you need to perform the following steps: 因此,要解决此问题,您需要执行以下步骤:

  1. Install Flask-CORS: 安装Flask-CORS:

     pip install flask-cors 
  2. Include this code in your Flask application (probably __init__.py): 在Flask应用程序中包含此代码(可能是__init__.py):

     from flask_cors import CORS CORS(app) 

That's it! 而已!

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

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