解決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)

执行结果

相关推荐
larance7 小时前
Gunicorn + Nginx+systemd 配置flask
nginx·flask·gunicorn
NuageL9 小时前
原始Json字符串转化为Java对象列表/把中文键名变成英文键名
java·spring boot·json
摇滚侠11 小时前
解释一下 JSON 文件中,能不能写注释,postman 中,定义 json 格式的接口参数,能写注释吗
json
林开落L11 小时前
从入门到了解:Protobuf、JSON、XML 核心解析(C++ 示例)
xml·c++·json·protobuffer·结构化数据序列化机制
酒精检测仪13 小时前
Elpis 总结
低代码·json
历程里程碑14 小时前
普通数组-----除了自身以外数组的乘积
大数据·javascript·python·算法·elasticsearch·搜索引擎·flask
Hello.Reader1 天前
Flink 对接 Azure Blob Storage / ADLS Gen2:wasb:// 与 abfs://(读写、Checkpoint、插件与认证)
flink·flask·azure
Coinsheep1 天前
SSTI-flask靶场搭建及通关
python·flask·ssti
IT实战课堂小元酱1 天前
大数据深度学习|计算机毕设项目|计算机毕设答辩|flask露天矿爆破效果分析系统开发及应用
人工智能·python·flask
码农阿豪1 天前
Flask应用上下文问题解析与解决方案:从错误日志到完美修复
后端·python·flask