【问题标题】:Trying to Request Data (POST) from FLASK API with Java Script尝试使用 Java 脚本从 FLASK API 请求数据(POST)
【发布时间】:2020-12-28 08:37:21
【问题描述】:

我目前正在尝试从我的 API 中使用 Java Script 请求数据,但它不起作用。 每次我发布我都会收到错误消息,即“TypeError:'NoneType' 对象不可下标”在 FLASK 中。 我的 API 代码:

#http://127.0.0.1:5000/fnd
@app.route('/fnd', methods=['POST'])
def fnd():
    content = request.json
    return jsonify(content['Text'])

对于我正在使用 JQuery AJAX 请求的帖子

$(function ()
{
    var output = $('#output');
    $('#checkonfake').on('click',function(){
        var texttocheck = $('#texttocheck').val();
        var datad = {"Text": texttocheck}
        console.log(datad);
        if(texttocheck != ""){
              $.ajax(
                {
                    dataType: "json",
                    type: 'POST',
                    data: 
                    { 
                        datad
                    },
                    url: 'http://127.0.0.1:5000/fnd',
                    success: function (result) 
                    {
                        console.log(result);
                    },
                    error: function () 
                    {
                        console.log("error");
                    }
                });
    }
})
});

我有一个输入框和一个按钮,只要我按下按钮,请求就会被发送出去。

【问题讨论】:

  • 如果我用 POSTMAN 试试,结果如下<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>405 Method Not Allowed</title> <h1>Method Not Allowed</h1> <p>The method is not allowed for the requested URL.</p>
  • 您收到该错误,因为content 是空的。得到The method is not allowed for the requested URL 的原因是def fnd() 的方法与您在POSTMAN 中使用的方法不同。

标签: javascript python jquery flask post


【解决方案1】:

您可以通过字符串将代码更改为:

#http://127.0.0.1:5000/fnd
@app.route('/fnd', methods=['POST'])
def fnd():
    s_json = request.get_data(as_text=True)
    obj = json.loads(s_json)
    return jsonify(obj['Text'])

并将 html 代码更改为:

datad = {"aaa":"aaaa", "bbb":"bbb","Text":"Text"}
$.ajax(
    {
        dataType: "json",
        type: 'POST',
        data: JSON.stringify(datad),
        url: 'http://127.0.0.1:5000/fnd',
        success: function (result)
        {
            console.log(result);
        },
        error: function ()
        {
            console.log("error");
        }
    });

或者如果你想使用 json

@app.route('/fnd', methods=['POST'])
def fnd():
    return jsonify(request.form["Text"])
datad = {"aaa":"aaaa", "bbb":"bbb","Text":"Text"}
 $.ajax(
    {
        dataType: "json",
        type: 'POST',
        data: datad,
        url: 'http://127.0.0.1:5000/fnd',
        success: function (result)
        {
            console.log(result);
        },
        error: function ()
        {
            console.log("error");
        }
    });

顺便说一句:
我在 flask.palletsprojects.com 中找不到 request.json 的信息
所以.. 我不知道这个参数的含义以及为什么它没有

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多