在使用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)
执行结果
文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...