Vueでaxiosを使用してドメイン間データを要求する方法
1、axiosはjsonpをサポートしていません.axiosの著者はjsonpがあまり友好的ではないと思っているので、CORS方式でもっときれいにすることをお勧めします.
2、axiosを使用して要求を送信する場合、サーバー側の設定
結果が正確に得られる.
3、例:
node.jsコード
echarts.vueコード:
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コード:
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();
}
}