likes
comments
collection
share

webpack 跨域 proxy url地址后面被匹配的坑 模糊 绝对地址

作者站长头像
站长
· 阅读数 72

错误的示范

proxy: {
  //配置跨域
  '/api': {
    target: 'https://xx.xx.com:18083',
    changOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  },
  '/user': {
    target: 'https://xx.xx.com/as',
    changOrigin: true,
    pathRewrite: {
      '^/user': ''
    }
  },
  '/qq': {
    target: 'https://api.weixin.qq.com/',
    changeOrigin: true,
    pathRewrite: {
      '^/qq': ''
    }
  }

}

获取接口时

// 微信请求
get_token(url) {
return axios({
  method: 'get',
  baseURL: process.env.NODE_ENV === 'development' ? '/qq' : 'https://api.weixin.qq.com/',
  url,
  timeout: 10000,
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
}).then(
  (response) => {
    return checkStatus(response)
  }
).then(
  (res) => {
    return checkCode(res)
  }
)
},
// 用公众号信息和code获取accessToken和openid
accessToken: async function(url) {
  const res = await http.get_token(url)
  if (res.status === 200) {
    const { access_token, openid } = res.data
    const userUrl = `sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
    this.getUserInfo(userUrl)
  }
},

里面的userinfo和配置的跨域里的/user

const userUrl = `sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`

解决方法:

  • /user改个名字(只要包含就会匹配,不包含就行)。如:/userurl
proxy: {
  //配置跨域
  '/api': {
    target: 'https://xx.xx.com:18083',
    changOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  },
  '/userurl': {
    target: 'https://xx.xx.com/as',
    changOrigin: true,
    pathRewrite: {
      '^/userurl': ''
    }
  },
  '/qq': {
    target: 'https://api.weixin.qq.com/',
    changeOrigin: true,
    pathRewrite: {
      '^/qq': ''
    }
  }

}