vue使用axios請求數據跨域解決(proxy)


proxy是什么?

proxy是ES6中就存在的,用於修改某些操作的默認行為,可以理解成在目標對象前設一個攔截層,因此也叫“代理器”

vue中使用proxy代理

Vue 框架開發的時候,會遇到跨域的問題,可在config/index.js 里配置proxyTable內容,使用proxy 代理。

module.exports = {
   publicPath:'./',// npm run build 之后的資源路徑默認 ‘/’
   devServer:{
     proxy:{
        '/hehe':{
          target:"http://ustbhuangyi.com/", //目標服務器
          changeOrigin:true,//是否改變請求源
          pathRewrite:{ //路徑重寫
            "^/hehe":''
          }
        }
        // "/xixi":{
        //   target:'http://www.baidu.com',
        //   changeOrigin:true,
        //   pathRewrite:{
        //     "^/xixi":''
        //   }
        // }
     }
   } 
}

然后在axios請求中

//get請求
export const  getRecommentList=()=>{
 return new Promise((resolve,reject)=>{
  let url='/hehe/music/api/getDiscList'
  axios.get(url)
  .then((data)=>{
   resolve(data)
  })
  .catch((err)=>{
    reject(err)
  })
 })
}
//post請求
export const  getRecommentList=()=>{
 return new Promise((resolve,reject)=>{
  let url='/hehe/music/api/getDiscList'
  let data={
    firstName: 'Fred',
    lastName: 'Flintstone'
    },
  axios.post(url,data)
  .then((data)=>{
   resolve(data)
  })
  .catch((err)=>{
    reject(err)
  })
 })
}


免責聲明!

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



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