解決flask-restful提示Did not attempt to load JSON data 问题

在使用flask-restfull进行API开发的时候。一旦我使用类似下面的代码从url或者form中获得参数就会出现报错:Did not attempt to load JSON data because the request Content-Type was not 'application/json'。

代码如下:

复制代码
# Flask_RESTFUl数据解析
from flask import Flask,render_template
from flask_restful import Api,Resource
from flask_restful.reqparse import RequestParser

app = Flask(__name__)
api = Api(app)

class RegisterView(Resource):
    def post(self):
        # 建立解析器
        parser = RequestParser()
        # 定义数据的解析规则
        parser.add_argument('uname',type=str,required=True,help='用户名验证错误',trim=True,location="args")
        # 解析数据
        args = parser.parse_args()
        # 正确,直接获取参数
        print(args)
             # 错误,回馈到前端
        # 响应数据
        return {'msg':'注册成功'}
    
# 建议映射关系
api.add_resource(RegisterView,'/register')

if __name__=="__main__":
    app.run(debug=True)

执行结果:

解决办法:

增加location的来源

parser.add_argument('uname',type=str,required=True,help='用户名验证错误',trim=True,location="args")

复制代码
# Flask_RESTFUl数据解析
from flask import Flask,render_template
from flask_restful import Api,Resource
from flask_restful.reqparse import RequestParser

app = Flask(__name__)
api = Api(app)

class RegisterView(Resource):
    def post(self):
        # 建立解析器
        parser = RequestParser()
        # 定义数据的解析规则
        parser.add_argument('uname',type=str,required=True,help='用户名验证错误',trim=True,location="args")
        # 解析数据
        args = parser.parse_args()
        # 正确,直接获取参数
        print(args)
             # 错误,回馈到前端
        # 响应数据
        return {'msg':'注册成功'}
    
# 建议映射关系
api.add_resource(RegisterView,'/register')

if __name__=="__main__":
    app.run(debug=True)

执行结果

相关推荐
学习3人组12 小时前
业务主表+JSON自定义字段
java·spring boot·json
Car1217 小时前
在vscode中添加一个tasks.json实现 rt thread的scons编译功能
vscode·json·build·scons
学习3人组17 小时前
基于 主表 + JSON 自定义字段的条件查询
json
weixin199701080161 天前
[特殊字符] RESTful API 接口规范详解:构建高效、可扩展的 Web 服务(附 Python 源码)
前端·python·restful
XMYX-01 天前
28 - Go JSON 数据操作
开发语言·golang·json
Promise微笑2 天前
Geo专家于磊:Json-LD优化实战SOP与双核四驱体系
大数据·人工智能·重构·json
专注VB编程开发20年2 天前
json和python元组,列表,字典对比
开发语言·python·json·php
奇树谦2 天前
深度解析 compile_commands.json:源码到目标码映射的核心枢纽
json
alwaysrun2 天前
C++之轻量级JSON序列库jsoncpp
c++·json·编程语言
彭于晏Yan2 天前
HttpServletRequest 如何读取JSON请求体
spring boot·后端·json