【问题标题】:Cannot post form data to flask using fetch api无法使用 fetch api 将表单数据发布到烧瓶
【发布时间】:2019-10-12 03:29:19
【问题描述】:

我在将数据发布到我的烧瓶服务器时遇到问题。当我使用邮递员时,示例数据发布得很好,但我不能从前端做到。

表单是动态生成的,看起来像这样

<div class="container" id="form-wrapper">
      <form id="comment-form" method="POST" onsubmit="send_comment(event)" class="border p-4 mt-4 rounded">
            <legend class="border-bottom mb-4">Register</legend>
                 <div class="form-group">
                      <label for="comment">Comment</label>
                            <textarea rows="3" class="form-control" id="comment" aria-describedby="name_help" name="comment"</textarea>
                            <input type="hidden" class="form-control" id="geom" name="geom" value="${coords25832[0]} ${coords25832[1]}">
             </div>
             <div class="form-group">
                 <button type="submit" class="btn-sm btn-primary">Save</button>
             </div>
      </form>
 </div>

这是发送数据的函数

function send_data(event) {
    event.preventDefault();

    let data = new FormData();
    data.comment= document.querySelector('form #comment').value;
    data.geom = document.querySelector('form #geom').value;

// Example data
//data = {"comment":"sd","geom":"567398.6224792203 7027428.422090762"}


fetch(`${baseurl}/api/comment`,
{
    method: "POST",
    headers: new Headers({
        //'Content-Type': 'application/x-www-form-urlencoded'
        'Content-Type': 'application/json'
    }),
    body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
.catch(function (error) {  
    console.log('Request failure: ', error);  
});

最后是我的路线。我正在尝试获取发布的数据。我已删除代码以保存到下面的 db 等。我只是想在服务器端获取数据。但它失败了,我不明白为什么?我只是想发布 json 或表单数据,但我无法让它工作,我似乎无法获取发布的数据?不确定是前端问题还是后端问题?

@mod.route(/comment', methods=['POST'])
def map_comment():
    if request.method == "POST":
        print("I am a post")
        if request.form:
            print("I have form data")
            #print(request.form['kommentar'])
        if request.data:
            print("I have data")
        if request.json:
            print("I have json")
            # Do stuff with the data...
        else:
            print("fail)

【问题讨论】:

    标签: post flask python-requests


    【解决方案1】:

    首先你的端点缺少返回值:

    from flask import jsonify
    
    @mod.route('/comment', methods=['POST'])
    def map_comment():
        if request.method == "POST":
            print("I am a post")
            if request.form:
                print("I have form data")
                #print(request.form['kommentar'])
            if request.data:
                print("I have data")
            if request.json:
                print("I have json")
                # Do stuff with the data...
                return jsonify({"message": "OK"})
            else:
                print("fail")
    
            return jsonify({})
    

    并且 POST 的数据应该被格式化为 JSON,这样 Flask 才能成功解析它。

    {
        method: "POST",
        headers: new Headers({
            //'Content-Type': 'application/x-www-form-urlencoded'
            'Content-Type': 'application/json'
        }),
        body: JSON.stringify(data)
    })
    

    由于错误的 json 格式,服务器在访问 request.json 时引发异常。

    【讨论】:

    • 我的路线稍后有一个返回值,但没有显示将其添加到帖子中。但是,按照您的建议将我的数据格式化为 JSON 有效!发送到服务器的数据似乎以字节形式发送回来? b'{"comment":"test","geom":"567398.6224792203 7027428.422090762"}' 是吗。我期待在 request.json 语句中捕获它?我真的必须将字节转换回字符串吗?好像不对
    • 如果你想要一个字典,请使用request.get_json()
    • get_json 工作正常。谢谢!我感到困惑的是,使用邮递员可以正常工作,通过 fetch API 发布 json 对象并且它不起作用,get_json() 返回 None。
    猜你喜欢
    • 2019-06-06
    • 2022-11-16
    • 1970-01-01
    • 2019-06-20
    • 2021-01-14
    • 2018-03-20
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多