您的位置:首页 > 编程语言 > Python开发

Flask: Ajax 设置Access-Control-Allow-Origin实现跨域访问;Ajax页面底部自动加载

2016-06-26 10:31 651 查看

更新:


Vue+Flask轻量级前端、后端框架,如何完美同步开发 可以完美实现跨域调试,不需要JSONP,也不需要服务器端设置

'Access-Control-Allow-Origin'



问题:

网页上(client)有一个ajax请求,Flask sever是直接返回 jsonify。

然后ajax就报错:No 'Access-Control-Allow-Origin' header is present on the requested 

原因:

ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。

即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。

官方问题说明:

“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs
into GETs for remote-domain requests.

如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。

因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。

例如:客户端的域名是www.client.com,而请求的域名是www.server.com

如果直接使用ajax访问,会有以下错误

XMLHttpRequest cannot load http://www.server.com/xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.

解决:

在被请求的Response header中加入header,

一般是在Flask views.py

@app.route('/articles_list/contents/')
def json_contents():
response = make_response(jsonify(response=get_articles(ARTICLES_NAME)))
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST'
response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return response


加上以上三行header,ajax调试时就不会报错

WebStorm 调试 Ajax

1. 略微修改被调试的 html,比如 ajax script里原来指向 server的相对路径,改为绝对路径:

getEntries = function () {
$.ajax({
type:"get",
url:"http://localhost:5000/articles_list/contents/", # 修改为绝对路径
async:true,
dataType: 'json',

2. Chrome 安装 JetBrains IDE support 插件 Extension

3. 启动本地Flask Sever,准备响应 ajax

4. WebStrom 在被调试 html文件 里设置断点,一般为 script function内部第一行

5. 点击 Debug

有时等时间长了,Debug也没返回,查看一下Debug -> Console 和 Flask Sever,可能显示:

  File "C:\Users\xxx\Anaconda2\lib\socket.py", line 307, in flush

    self._sock.sendall(view[write_offset:write_offset+buffer_size])

error: [Errno 10053]

这时,重启Flask sever。点击 Debug 工具右侧的 “Async”,再重新Debug

6. 成功!可以单步调试啦!



Ajax页面底部自动加载

参考我的 git: https://code.csdn.net/Kevin_QQ/flask_ajax_scroll/wikis


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python Flask WebStorm Ajax