欢迎加QQ交流:
2
0
2
3

vue3跨域配置

先看图:

图1:是直接获取数据,但是获取失败,这是典型的跨域。

图2  图3 是通过跨域配置后通过相同的接口拿到的数据。

1

2

3

接下来看看相关配置:

首先就是 在 src 下 创建一个 vue.config.js 文件,然后在文件里配置 参数:

module.exports = {
  devServer: {
    Proxy: {
      '/api': {
        target: 'http://www.xiongmaoyouxuan.com',
        ws: true,
        changeOrigin: true
      }
    }
  }
}
 
如下图:

然后在 工具文件里去 封装 axios:

(这里我省略了线上环境和开发环境域名的判断,请求拦截,响应拦截,参数序列,优化等等,主要是测试配置跨域。)

import axios from 'axios'

const $http = axios.create({
  baseURL: 'http://www.xiongmaoyouxuan.com/api', // 所有的请求地址前缀部分
})
const $get = function(url,param,fn){
  $http.get(url,{params:param}).then(function(res){
    fn(res.data)
  }).catch(function(err){
    console.log(err)
  })
}
export default{$get}
 
如下图:

最后一步使用:

<script>
  import {onMounted} from 'vue'
  import api from '../../../utils/util'
  export default {
    setup() {
      onMounted(() => {
        api.$get(
          "/tabs?sa=",
            {},
            res => {
                console.log('测试', res)
            }
        )
      })

      return {}
    },
  }
</script>
 
如下图:

稳的一批,整起来

posted @ 2022-06-16 14:54  常安·  阅读(983)  评论(1编辑  收藏  举报