vue2.x實現跨域(proxytable)請求fetch/axios


通過vue-cli2.x創建的項目實現跨域
1.找到config文件夾
2.在inde.js文件中找到proxytable{}
3.添加代碼
proxyTable: {
      '/api': {
        target: 'http://xxxxxx.com', // 請求的接口的域名
        // secure: false,  // 如果是https接口,需要配置這個參數
        changeOrigin: true, // 如果接口跨域,需要進行這個參數配置
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    //當你發起請求時前面加上'/api/'就代表着'http://xxxxxx.com'
    // 注意: '/api' 為匹配項,target 為被請求的地址,因為在 ajax 的 url 中加了前綴 '/api',而原本的接口是沒有這個前綴的,所以需要通過 pathRewrite 來重寫地址,將前綴 '/api' 轉為 '/'。如果本身的接口地址就有 '/api' 這種通用前綴,就可以把 pathRewrite 刪掉。
通過fetch請求
 1 export defalut{
 2     created(){
 3         fetch('地址',{
 4             method:'post',//請求的方式
 5             //請求頭
 6             headers:{
 7                 'Content-type':'application/json',
 8                 token:'',
 9             },
10             // body:'post請求的參數',
11             body:JSON.stringify({username:,password:})
12         })
13         .then(result=>{//請求成功的結果
14             console.log(result)
15         })
16     }
17 }
通過axios請求
先下載axios,npm install axios
在main.js中引入配置
1 import axios form 'axios'
2 //設置請求的headers
3 axios.defaults.headers.common['token']=''
4 axios.defaults.headers.post['Content-type']='application/json'
5 Vue.prototype.$axios=axios
在組件中使用axios
 1 export defalut{
 2     created(){
 3         this.$axios.post('地址',{
 4             //參數
 5         })
 6         .then(data=>{
 7             console.log(data)
 8         })
 9     }
10 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM