vue 跨域

后端如果已经设置了CORS,那么直接访问是可以获取数据的

 axios.get('http://localhost:80/get_word_list').then(
    (response) => {
      console.log(response.data)
    },
    (err) => {
      console.log(err)
    }
  )

如果后端没有设置CORS,那么按照上面的访问方式会出错 

首先设置config/index.js 文件

注意: '/api' 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/'。如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉。

使用的时候只需要用 /api/get_word 的形式就行

 axios.get('/api/get_word_list').then(
    (response) => {
      console.log(response.data)
    },
    (err) => {
      console.log(err)
    }
  )

  axios.get('/api/get_word_random').then(
    (response) => {
      console.log(response.data)
    },
    (err) => {
      console.log(err)
    }
  )

成功获取数据

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1622302