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

执行结果

相关推荐
java1234_小锋7 小时前
【AI大模型舆情分析】微博舆情分析可视化系统(pytorch2+基于BERT大模型训练微调+flask+pandas+echarts) 实战(上)
人工智能·flask·大模型·bert
Andy Dennis8 小时前
FTP局域网小网站V2.3——安全、批量、有序,体验全新进化
服务器·flask·ftp工具
Async Cipher10 小时前
RESTful API
restful
HDO清风1 天前
CASIA-HWDB2.x 数据集DGRL文件解析(python)
开发语言·人工智能·pytorch·python·目标检测·计算机视觉·restful
AIFQuant1 天前
如何利用免费股票 API 构建量化交易策略:实战分享
开发语言·python·websocket·金融·restful
沈浩(种子思维作者)1 天前
铁的居里点(770度就不被磁铁吸了)道理是什么?能不能精确计算出来?
人工智能·python·flask·量子计算
Andy Dennis1 天前
FTP局域网功能小网站V2_2
服务器·flask·html5
talle20211 天前
Hive | json数据处理
hive·hadoop·json
90的程序爱好者1 天前
flask入门
后端·python·flask
一起养小猫1 天前
Flutter for OpenHarmony 实战:网络请求与JSON解析完全指南
网络·jvm·spring·flutter·json·harmonyos