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

执行结果

相关推荐
甄超锋1 分钟前
python sqlite3模块
jvm·数据库·python·测试工具·django·sqlite·flask
杨DaB16 小时前
【SpringBoot】Swagger 接口工具
java·spring boot·后端·restful·swagger
Yn31218 小时前
在 Python 中使用 json 模块的完整指南
开发语言·python·json
0wioiw021 小时前
Python基础(Flask①)
后端·python·flask
Q_Q5110082851 天前
python的软件工程与项目管理课程组学习系统
spring boot·python·django·flask·node.js·php·软件工程
wyiyiyi2 天前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
麦麦大数据2 天前
F004 新闻可视化系统爬虫更新数据+ flask + mysql架构
爬虫·mysql·flask·可视化·新闻
S01d13r3 天前
gunicorn + flask 处理高并发请求
python·flask·gunicorn
千层冷面3 天前
Flask ORM 查询详解:Model.query vs db.session.query vs db.session.execute
数据库·python·django·flask
陈涛5753 天前
5个最好用的 JSON 工具推荐:让数据处理变得简单高效
json