Vue

Vue<解决本地请求URL时出现的跨域问题>

2019-10-12  本文已影响0人  誰在花里胡哨
问题:
image.png
此处是打算通过请求一个URL地址,获得json数据,但是直接用axios请求的话,就会报以上错误(跨域问题)
image.png
通过以上错误可以看出,是我本地192.168.0.115:8080请求时,出现的错误。而这篇文章主要解决的就是本地请求时出现的跨域问题。(🎈注意哦,是解决 本地 请求出现的问题!!!如果是通过其他api请求出现跨域这种问题,那就不是你前端所能解决的了,一般是服务端解决的问题)
解决方案:

⚓首先需要 npm install -s http-proxy-middleware,用 http-proxy-middleware 中间件作为代理;

config文件下找到index.js

image.png
🙃注意了!!在修改完配置后,需要重新 npm run dev 一下,不然不起效果的~~😊
proxyTable: { // 配置如下代码
      '/api': {
        target:'https://xxxxxx/dictionary/data_dictionary_front.json', // 你请求的第三方接口
        changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite:{  // 路径重写,
          '^/api': ''  // 替换target中的请求地址,也就是说以后你在请求https://xxxxxx/dictionary/data_dictionary_front.json这个地址的时候直接写成/api即可。
        }
      }
    },

因为我需要把请求到的json数据作为一个字典表来使用,所以需要做全局配置。SO~~
main.js中(这样就不会报错了~~)

axios({
    url:'/api',
    baseURL: '',
    method:'GET'
  }).then(res=>{
    console.log(res.data)
    Vue.prototype.$dict = res.data;
  })

这样就算是解决本地请求的问题了,为了解决本地和线上都要请求json数据问题,做了一下优化

if (process.env.NODE_ENV === 'development') {
  // dev
  axios({
    url:'/api',
    baseURL: '',
    method:'GET'
  }).then(res=>{
    console.log(res.data)
   sessionStorage.setItem('dictionary',JSON.stringify(res.data))
    Vue.prototype.$dict = JSON.parse(sessionStorage.dictionary);
  })
} else {
  // build
  axios({
    url:' https://xxxxxx/dictionary/data_dictionary_front.json',
    baseURL: '',
    method:'GET'
  }).then(res=>{
    console.log(res)
   sessionStorage.setItem('dictionary',JSON.stringify(res.data))
    Vue.prototype.$dict = JSON.parse(sessionStorage.dictionary);
  })
}

当在 dev 时就直接走咱们配置的,build时就直接请求原地址就行了~~~

上一篇下一篇

猜你喜欢

热点阅读