30. Flask 設置headers Access-Control-Allow-Origin實現跨域訪問

需求

通常前端若是直接發起請求至後臺,都會出現跨域問題。報錯以下:html

17 Vue 使用 vue-resource 發起get、post、jsonp請求.html:1 Access to XMLHttpRequest at 'http://127.0.0.1:5000/login' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.前端

下面示例Flask設置headers['Access-Control-Allow-Origin']='*'頭信息,解決跨域api問題。vue

Flask示例以下:

from flask import Flask, jsonify,request,make_response

# 實例化app
app = Flask(import_name=__name__)


@app.route('/login', methods=["GET","POST"])
def login():

method = request.method

res = make_response(jsonify(token=123456, gender=0, method = method)) # 設置響應體
res.status = '200' # 設置狀態碼
res.headers['Access-Control-Allow-Origin'] = "*" # 設置容許跨域
res.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
return res

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

此時,設置好了這兩個headers的參數,以下:web

res.headers['Access-Control-Allow-Origin'] = "*"  # 設置容許跨域
res.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'

則會容許 get、post 的跨域請求,下面前端測試以下。json

前端測試執行跨域get、post請求

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 1.導入vue.js庫 -->
<script src="lib/vue.js"></script>
<!-- 2.導入vue-resource,注意:須要先引入vue.js -->
<script src="lib/vue-resource-1.5.1.js"></script>

</head>
<body>

<div id="app">
<input type="button" value="get請求" @click="getInfo">
<input type="button" value="post請求" @click="postInfo">
<input type="button" value="jsonp請求" @click="jsonpInfo">
</div>

<script>

// 2. 建立一個Vue的實例
var vm = new Vue({
el: '#app',
data: {},
methods: {
getInfo() { // 發起get請求
// 當發起get請求以後, 經過 .then 來設置成功的回調函數
this.$http.get('http://127.0.0.1:5000/login').then(function (result) {
// 經過 result.body 拿到服務器返回的成功的數據
// console.log(result.body)
})
},
postInfo() { // 發起 post 請求 application/x-wwww-form-urlencoded
// 手動發起的 Post 請求,默認沒有表單格式,因此,有的服務器處理不了
// 經過 post 方法的第三個參數, { emulateJSON: true } 設置 提交的內容類型 爲 普通表單數據格式
this.$http.post('http://127.0.0.1:5000/login', {}, { emulateJSON: true }).then(result => {
console.log(result.body)
})
},
},

});

</script>

</body>
</html>

瀏覽器執行前端請求以下:flask

  • 執行get請求
  • 執行post請求

此時get和post均可以跨域請求了。api


本文分享自微信公衆號 - 海洋的漁夫(DevOpsCommunity)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。跨域

相關文章
相關標籤/搜索