源碼:
<template>
<div>
{{info}}
</div>
</template>
<script>
import Axios from "axios"
export default {
data () {
return {
info: 'ving info1'
}
},
mounted () {
var that = this
Axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (that.info = response.data.sites))
.catch(function (error) { // 請求失敗處理
console.log(error);
});
}
}
</script>
異常圖:

原因:
出現這個問題主要是跨域原因
解決辦法:
第一步:根目錄新建 ‘ vue.config.js ’ 文件

填入內容:
module.exports = {
configureWebpack:{
resolve:{
// 給路徑起別名
alias:{
'assets': '@/assets',
'common': '@/common',
'components': '@/components',
'network': '@/network',
'views': '@/views'
}
}
},
devServer:{
proxy:{
'/json_demo':{
// 跨域的服務器地址
target: 'https://www.runoob.com/try/ajax/json_demo.json',
// 是否允許跨域
changeOrigin: true,
// 替換掉請求路徑的/json_demo“”
pathRewrite:{'^/json_demo': ""}
},
}
}
}
修改Vue頁面
<template>
<div>
{{info}}
</div>
</template>
<script>
import Axios from "axios"
export default {
data () {
return {
info: 'ving info1'
}
},
mounted () {
var that = this
Axios
.get('/json_demo')
.then(response => (that.info = response.data.sites))
.catch(function (error) { // 請求失敗處理
console.log(error);
});
}
}
</script>
