flask-restful 封装接口, ie8/9 下 跨域调用的问题,快被折磨死了。

2017-10-24 22:01:06 +08:00
 xuyl

接口逻辑如下


from flask import Flask, request
from flask_restful import reqparse, abort, Api, Resource
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
api = Api(app)

class Suggest(Resource):
	#decorators = [check_http_headers, check_request_frequency]
	def __init__(self):
		super(SuggestApi, self).__init__()
		self.parser = reqparse.RequestParser()
		self.parser.add_argument('name', type=str, required=True, help='name 不能空')
                self.parser.add_argument('age', type=int, required=True, help='age 不能空')
		self.args = self.parser.parse_args()

	def post(self):
    	       name = self.args['name']
               age = self.args['age']
               return {'name': name, 'age': age}, 200
               #return request.data.decode('utf-8')

api.add_resource(Suggest, '/api/v1/suggest')

if __name__ == '__main__':
    app.run(debug=True)

前端测试页面如下(因为不支持 cors 跨域, 所以用了 xdomain request)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button>发送 post 请求</button>
	<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js"></script>
	<script>
		$(function() {
			$('button').on('click',function() {
				var param = {name:'test', age: 25};
				if(!$.support.cors) {
					param = JSON.stringify(param);
				}

				$.ajax('http://127.0.0.1:5000/api/v1/suggest',{
					type:'post',
					dataType:'json',
					data:param,
					success:function(resp) {
						console.log(resp);
					}
				})
			})
		})
	</script>
</body>
</html>

测试结果

只要用了参数解析reqparse.RequestParser(),并且required=True, 调用接口就是 400 错误;将required=True去掉,虽然不再 400 错误,但并不能在self.args中获取到参数, 测试参数是在request对象里的data属性里面。

求助?

参数解析帮了很大忙,不想因为兼容 ie8 就不用参数解析了,有什么办法能做到让 ie8 兼容呢?

3998 次点击
所在节点    Flask
25 条回复
xuyl
2017-10-26 13:49:57 +08:00
@vZexc0m 你看我主帖里,我也用了 flask_cors,跨域是没问题的,是参数解析的问题。
vZexc0m
2017-10-26 15:42:53 +08:00
@xuyl 试试不用 flask_result,直接用框架看看有没有问题
xuyl
2017-10-28 21:01:08 +08:00
@vZexc0m 多谢你的回复,参数在 request.data 里可获取到,但不用 flask-restful,对于规范化接口比较痛苦。
vZexc0m
2017-10-30 09:13:48 +08:00
restful 只是一种规范而已,不插件也可以实现
ropon
2019-07-06 13:13:06 +08:00
请问解决了么? abort 抛出异常,状态码 400 就会出现跨域
![]( https://i.bmp.ovh/imgs/2019/07/9ab5c8f3cc91dcae.jpg)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/400386

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX