10、axios請求以及跨域問題,前端解決方法。11、后端-nginx解決方法


https://www.jianshu.com/p/7a9fbcbb1114       axios 簡書文檔

安裝 

cnpm install --save axios

引入 axios

前端解決跨域

flask 后端代碼,

from flask import render_template, json, jsonify,Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)

@app.route('/api/getdata')
def index():
    data={'name':'test'}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0')
tets.py

App.vue 前端跨域配置methods 請求后端參數

<template>
  <div id="app">
    <h1>Hello App!</h1>
    <p>
      <!-- 使用 router-link 組件來導航. -->
      <!-- 通過傳入 `to` 屬性指定鏈接. -->
      <!-- <router-link> 默認會被渲染成一個 `<a>` 標簽 -->
      <router-link to="/foo">Go to Foo</router-link>
      <router-link to="/bar">Go to Bar</router-link>

<!--      <router-link to="/user/123/">user</router-link>      &lt;!&ndash;動態匹配路由 to url格式必須正確,這里這里供參考格式&ndash;&gt;-->
      <router-link :to="{ name: 'user', params: { userid }}">User</router-link>
    </p>


    <!-- 路由出口 -->
    <router-view></router-view>     <!-- 路由匹配到的組件將渲染在這里 -->
    <h1> {{name_data}}</h1>
  </div>

</template>


<script>
  export default {
    name:'app',
    data() {
      return {
        userid: "1233232",
        name_data:'',    // 定義name返回值

      }
    },
    methods: {    // 掛載完成出發,跨域操作
      getdata(){
        this.$axios.get('/api/getdata').then((response)=>{
          console.log(response.data)
          this.name_data = response.data.name  // 拿到后返回name值
        }).catch((response)=>{
          console.log(response)
        })
      }
    },
    mounted() {
      this.getdata()
    }

  }
</script>
App.vue

indwx.js 前端解決跨域

proxyTable: {
      '/api': {
        changeOrigin: true,
        target: 'http://10.12.30.70:5000',  
        pathRewrite: {
          '^/api': '/api'
        }
      }
    },

main.js
index.js

接收到 后端返回的  name:test. 前端渲染

flaks后端解決跨域:

生產環境中打包,沒有前端跨域,所以使用后端跨域

 

跨域是指瀏覽器A服務器B獲取的靜態資源,包括Html、Css、Js,然后在Js中通過Ajax訪問C服務器的靜態資源或請求。即:瀏覽器A從B服務器拿的資源,資源中想訪問服務器C的資源。
同源策略是指瀏覽器A服務器B獲取的靜態資源,包括Html、Css、Js,為了用戶安全,瀏覽器加了限制,其中的Js通過Ajax只能訪問B服務器的靜態資源或請求。即:瀏覽器A從哪拿的資源,那資源中就只能訪問哪。
同源是指:同一個請求協議(如:Http或Https)、同一個Ip、同一個端口,3個全部相同,即為同源。
 
前后端分離在開發調試階段本地的flask測試服務器需要允許跨域訪問,簡單解決辦法有
1、使用 flask_cors
pip3 install flask_cors
flask.py 后端代碼, 加上這一條即可
CORS(app, supports_credentials=True)
from flask import render_template, json, jsonify,Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app, supports_credentials=True)  # 加上這一條就實現跨域了

@app.route('/api/getdata')
def index():
    data={'name':'test'}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0'
test.py
App.vue   去掉 index.js中的 proxyTable。
<template>
  <div id="app">
    <h1>Hello App!</h1>
    <p>
      <!-- 使用 router-link 組件來導航. -->
      <!-- 通過傳入 `to` 屬性指定鏈接. -->
      <!-- <router-link> 默認會被渲染成一個 `<a>` 標簽 -->
      <router-link to="/foo">Go to Foo</router-link>
      <router-link to="/bar">Go to Bar</router-link>

<!--      <router-link to="/user/123/">user</router-link>      &lt;!&ndash;動態匹配路由 to url格式必須正確,這里這里供參考格式&ndash;&gt;-->
      <router-link :to="{ name: 'user', params: { userid }}">User</router-link>
    </p>


    <!-- 路由出口 -->
    <router-view></router-view>     <!-- 路由匹配到的組件將渲染在這里 -->
    <h1> {{name_data}}</h1>
  </div>

</template>


<script>
  export default {
    name:'app',
    data() {
      return {
        userid: "1233232",
        name_data:'',    // 定義name返回值

      }
    },
    methods: {    // 掛載完成出發,跨域操作
      getdata(){
        this.$axios.get('http://10.12.30.70:5000/api/getdata').then((response)=>{
          console.log(response.data)
          this.name_data = response.data.name  // 拿到后返回name值
        }).catch((response)=>{
          console.log(response)
        })
      }
    },
    mounted() {
      this.getdata()
    }

  }
</script>
View Code

 

可以添加頭部信息,在想要的時候添加頭部信息:

2、在想要的時候添加頭部信息:

@app.after_request
def af_request(resp):     
    """
    #請求鈎子,在所有的請求發生后執行,加入headers。
    :param resp:
    :return:
    """
    resp = make_response(resp)
    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return resp
View Code

 

nginx解決跨域問題
flask 后端
from flask import render_template, json, jsonify,Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
#CORS(app, supports_credentials=True)  # 加上這一條就實現跨域了

@app.route('/api/getdata')
def index():
    data={'name':'test'}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0'
test.py

 nginx配置

     location / {
            proxy_pass http://127.0.0.1:8080;    ###vue
        }
        location /api {
       proxy_pass http://127.0.0.1:5000;   ###后端服務
    }
nginx.config

 

 App.vue 中接口訪問nginx代理就可以


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM