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

执行结果

相关推荐
duansamve1 天前
Python3+Flask+PostgreSQL18+Vue3项目生产环境用docker如何部署?
python·docker·flask
duansamve1 天前
详解Flask中Session和Cookie
python·flask
duansamve2 天前
Flask中视图函数接收请求数据和返回响应实例
python·flask
xbzb2 天前
镜像到底存在哪:/var/lib/docker 的四级映射与 daemon.json 配置
docker·容器·json·镜像·daemon.json·四级
梅雅达编程笔记3 天前
退款之后钱货两空:Flask售后退款状态机加库存回滚加原路退回
flask·毕设·状态机·电商系统·退款·售后·myd电商
坤坤子吖3 天前
Linux网络编程:自定义应用层协议与 JSON 序列化
linux·服务器·网络·c++·笔记·json
code2cat3 天前
【随笔】结构化输出:JSON格式过关,业务数据就能入库吗
json·大语言模型
Thanks_ks4 天前
HTTP 请求方法与 RESTful 接口设计:GET 和 POST 到底怎么用
http·api·restful·状态码·get·post·接口设计
梅雅达编程笔记4 天前
忘记密码只能找客服:Flask邮箱验证码重置密码加限流防爆破
flask·限流·毕设·电商系统·myd电商·找回密码·邮箱验证码
hhcgchpspk5 天前
flask服务端页面预防被爬措施
后端·python·flask·网络爬虫·防爬