解決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 小时前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
ZhongruiRao18 小时前
Springboot+PostgreSQL+MybatisPlus存储JSON或List、数组(Array)数据
spring boot·postgresql·json
华农第一蒟蒻19 小时前
Java中JWT(JSON Web Token)的运用
java·前端·spring boot·json·token
一眼万里*e19 小时前
fish-speech语音大模型本地部署
python·flask·大模型
胡耀超20 小时前
知识图谱入门——8: KG开发常见数据格式:OWL、RDF、XML、GraphML、JSON、CSV。
xml·json·知识图谱·csv·owl·graphml·gml
程序员陆通20 小时前
Spring Boot RESTful API开发教程
spring boot·后端·restful
x-cmd1 天前
[241005] 14 款最佳免费开源图像处理库 | PostgreSQL 17 正式发布
数据库·图像处理·sql·安全·postgresql·开源·json
先知demons1 天前
js将对象的键和值分别归纳进对象,并将多层对象转化成数据的方法
javascript·vue.js·json
Midsummer啦啦啦2 天前
Python字符串转JSON格式指南
开发语言·python·json
前端 贾公子2 天前
Express内置的中间件(express.json和express.urlencoded)格式的请求体数据
中间件·json·express