Python 3 Flask Rest Api: "request.get_json()" gives TypeError: 'NoneType' object is not subscriptable

Python 3 Flask Rest Api: "request.get_json()" gives TypeError: 'NoneType' object is not subscriptable

我正在 python flask 中创建一个路由,它将作为 rest api 服务来注册用户。 当我尝试在 POST 方法中获取通过邮递员传递的 json 数据时,出现错误 TypeError: 'NoneType' object is not subscriptable

我对邮递员的要求: http://127.0.0.1:5000/register

原始输入:{"username":"alok","password":"1234"}

我的路线和功能:

@app.route('/register', methods=['GET', 'POST'])
def signup_user():
    data = request.get_json()
    return data['username']

据我所知,上面的函数应该 return : "alok"

但我收到错误:类型错误:'NoneType' 对象不可订阅

任何帮助将不胜感激

我花了几个小时上网,我从 flask 官方网站得到了答案

我在请求时没有设置 mimetype。
如果 mimetype 未指示 JSON(application/json,请参见 is_json()),则此 returns None。
request.get_json() 用于将数据解析为 JSON. 实际语法是 get_json(force=False, silent=False, cache=True)

参数
force – 忽略 mimetype 并始终尝试解析 JSON。
silent – 沉默解析错误并 return None 代替。
cache – 将解析后的JSON存储到return,以供后续调用。

所以最后我将代码更改为

@app.route('/register', methods=['GET', 'POST'])
def signup_user():
    data = request.get_json(force=True)
    return data['username']

已解决

Content-Type : application/json 添加到您的 Post API 请求的 header 中。