Vue中如何使用axios請求跨域數據

一、axios不支持jsonp,由於axios的做者以爲jsonp不太友好,推薦用CORS方式更爲乾淨;html

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

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

能夠正確獲得結果。node

三、實例:ios

node.js代碼express

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("開始執行請求");
});

echarts.vue代碼:json

<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>
相關文章
相關標籤/搜索