Vue中如何跨域請求數據(webpack、node.js和django中實現)


一、webpack中設置跨域:

webpack提供了配置代理的方法解決跨域:

1、在vue-cli項目中打開webpack.dev.cof.js,如下:

devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  }

其中,proxy: config.dev.proxyTable為配置代理。 

2、打開conifg目錄下的index.js,在 proxyTable中進行配置:

proxyTable: {
      '/api': { target: 'http://127.0.0.1:9999/',//設置你調用的接口域名和端口號,別忘了加http changeOrigin: true, secure: false, // 如果是https接口,需要配置這個參數 pathRewrite: { '^/api': '/'//這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可 } } }

3、配置好后,就可以獲取后台提供的接口,然后進行頁面的渲染了:

<script>
export default { methods: { getData() { this.$axios .get("/api/blog/data/") .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); } } }; </script>

二、axios請求的接口提供服務端設置跨域:

1、axios不支持jsonp,因為axios的作者覺得jsonp不太友好,推薦用CORS方式更為干凈;

2、在使用axios發送請求時,服務器端設置

res.header("Access-Control-Allow-Origin", "*")

可以正確得到結果。

3、實例:

3.1 node.js代碼

let express = require("express");
let app = express();
 
app.use("/public", express.static("public"));
 
app.get("/index", function(req, res, next){
    res.sendFile(__dirname + "/" + "views/index.html");
});
 
app.get("/get_data", function(req, res, next){
	res.header("Access-Control-Allow-Origin", "*");
    let response = {
    	title: '在Vue中使用echarts',
    	xAxisData: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"],
    	seriesData: [10, 26, 16, 20, 16, 30]
    };
    res.type('application/json');
    res.jsonp(response);
});
 
app.listen(8000, function(){
    console.log("開始執行請求");
});

3.2 django代碼:

settings.py中:

(1) 安裝 django-cors-headers:

pip install django-cors-headers

(2) 添加到已安裝的應用程序中:

INSTALLED_APPS  =(
     ... 
    ' corsheaders ', ... )

(3) 添加中間件類來收聽響應:

MIDDLEWARE  = [
    ... 
    # 跨域請求中間件 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ]

注意:要放在中間件(common.CommonMiddleware)的上面,涉及到請求響應的順序問題。

(4) 跨域配置:

在settings文件最后面添加如下所有代碼

# 跨域允許的請求方式,可以使用默認值,默認的請求方式為: # from corsheaders.defaults import default_methods CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) # 允許跨域的請求頭,可以使用默認值,默認的請求頭為: # from corsheaders.defaults import default_headers # CORS_ALLOW_HEADERS = default_headers CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', ) # 跨域請求時,是否運行攜帶cookie,默認為False CORS_ALLOW_CREDENTIALS = True # 允許所有主機執行跨站點請求,默認為False # 如果沒設置該參數,則必須設置白名單,運行部分白名單的主機才能執行跨站點請求 CORS_ORIGIN_ALLOW_ALL = True

echarts.vue代碼:

<template>
  <div>
    <div id="myChart">

    </div>
  </div>
</template>

<script>
  export default {
    methods: {
      drawLine(){
        // 基於准備好的dom,初始化echarts實例
        let myChart = this.$echarts.init(document.getElementById('myChart'));

        this.$axios.get("http://127.0.0.1:8000/get_data")
          .then(function(res){
            // 繪制圖表
            myChart.setOption({
              title: { text: res.data.title },
              tooltip: {},
              xAxis: {
                data: res.data.xAxisData
              },
              yAxis: {},
              series: [{
                name: '銷量',
                type: 'bar',
                data: res.data.seriesData
              }]
            });
          })
          .catch(function(err){
            console.log(err);
          })
      }
    },
    mounted(){
      this.drawLine();
    }
  }
</script>

<style>
#myChart{
  height: 500px;
}
</style>


免責聲明!

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



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