Vue中如何使用axios请求跨域数据

1、axios不支持jsonp,因为axios的作者觉得jsonp不太友好,推荐用CORS方式更为干净;

2、在使用axios发送请求时,服务器端设置

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

可以正确得到结果。

3、实例:

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("开始执行请求");
});

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>

猜你喜欢

转载自www.cnblogs.com/samve/p/10884808.html