vue中axios网络get请求封装。

一,配置了代理服务器,解决跨域

module.exports = {
    publicPath: /,    // 启动页地址
    outputDir: dist, // 打包的目录
    lintOnSave: true, // 在保存时校验格式
    productionSourceMap: false, // 生产环境是否生成 SourceMap
    devServer: {
        open: true, // 启动服务后是否打开浏览器
        host: 0.0.0.0,
        port: 8080, // 服务端口
        https: false,
        hotOnly: false,
        // 设置代理
        proxy:{
          /myDouyu:{
            target:http://open.douyucdn.cn/api/RoomApi,
            changeOrigin:true,
            pathRewrite:{
              ^/myDouyu:
            }
          }
        },
        before: app => { }
    },
}

二,封装get请求

// ajax请求的封装
import axios from "axios";
const baseUrl = /myDouyu
 
function ajax_get(path, params){
  return new Promise(resolve=>{
    axios.get(baseUrl + path, {params}).then(res=>{
      resolve(res.data)
    })
  })
}

const getLiveRooms = params => ajax_get(/live, params)
const getGames = () => ajax_get(/game)
const getDetail = del => ajax_get(del)


export {
  getLiveRooms,
  getGames,
  getDetail
}
经验分享 程序员 微信小程序 职场和发展