生成一個(gè)vue項(xiàng)目之后,開始寫請求,請求數(shù)據(jù),渲染到前端界面,有時(shí)候直接請求服務(wù)器上的接口,會(huì)遇到跨域問題,遇到跨域的時(shí)候,需要設(shè)置跨域代理~
1:進(jìn)入新建的項(xiàng)目之中,使用npm安裝axios模塊。
npm install axios --save

2:準(zhǔn)備json數(shù)據(jù)
自己寫了一個(gè)json數(shù)據(jù),放在服務(wù)器上,現(xiàn)在要通過vue項(xiàng)目調(diào)用數(shù)據(jù)
http://www.intmote.com/test.json
3:跨域問題,設(shè)置代理,利用proxyTable屬性實(shí)現(xiàn)跨域請求
在config/index.js 里面找到proxyTable :{} ,然后在里面加入以下代碼
proxyTable:{'/api':{target:'http://www.intmote.com',//設(shè)置你調(diào)用的接口域名和端口號(hào) 別忘了加httpchangeOrigin:true,//允許跨域pathRewrite:{'^/api':''//這個(gè)是定義要訪問的路徑,名字隨便寫 }}},

4:打開一個(gè)界面test.vue,開始寫請求數(shù)據(jù)的方法
在寫代碼之前,要記得引入import axios from 'axios'模塊。
methods:{getData(){axios.get('/api/test.json').then(response=>{console.log(response.data);},response=>{console.log("error");});}}
test.vue參考代碼:
<template><divid='app'>axios請求數(shù)據(jù)</div></template><script>import axios from 'axios'export default {? name: 'app',? data () {? ? return {? ? ? itemList: []? ? }? },? mounted () {? ? this.getData()? },? methods: {? ? getData () {? ? ? axios.get('/api/test.json').then(? ? ? ? response => {? ? ? ? ? console.log(response.data)? ? ? ? },? ? ? ? response => {? ? ? ? ? console.log('error')? ? ? ? }? ? ? )? ? }? }}</script>
6:再次運(yùn)行
ctrl+c退出,再次使用命令啟動(dòng)npm run dev
這個(gè)時(shí)候,我們可以看見,請求的數(shù)據(jù),返回值如下

打開network網(wǎng)絡(luò)請求,可以看見請求已經(jīng)代理完成~
http://localhost:8080/api/test.json

作者:祈澈菇?jīng)?/p>
鏈接:http://www.itdecent.cn/p/9be22b9c9336
來源:簡書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。