Vue3 使用 axios 实现跨域

Vue3 使用 axios 可以实现请求跨域问题

1.安装axios

npm install axios -S

2.引入axios 并配置为全局 $axios 对象

main.js

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
 
//createApp(App).mount('#app')

const app = createApp(App)
app.config.globalProperties.$axios = axios

app.mount('#app')

2. 配置转发

下面代码是 将   127.0.0.1 的 8080端口  中凡是 含有 /sina 的地址  转发至 http://192.168.1.31:80/ 下

其中 /sina 不改变,只改变IP和端口

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,

  //-----------------------Axios跨域请求-----------------------------------------
  devServer:{
    port:8080,//vue网页访问的端口
    host:"127.0.0.1",//vue网页访问的地址
    https:false,
    open:false,
    proxy: {
        '/sina': {  //为用于替换的的标识字符串
            target: 'http://192.168.1.31:80/',//Axios跨域请求的IP
            changeOrigin: true, 
            ws: true,
            pathRewrite: {
                '^/sina': '' //不改变
            }
        },
        /* 可以同步配置多个转发目标
        '/phpUrl': {  //为用于替换的的标识字符串
          target: 'http://192.168.1.8:8080/VueApi',//Axios跨域请求的IP
          changeOrigin: true, 
          ws: true,
          pathRewrite: {
              '^/phpUrl': '' //不用改
          }
       }  */
      
    }
  }
  //----------------------------------------------------------------------------

})

调用方式

其中地址   /sina/api/sessions  转发前 实际请求地址是  http://127.0.0.1:8080/sina/api/sessions

因为地址中 含有  /sina 符合转发条件 因此 axios 进行转发

转发后 实际请求地址是  http://192.168.1.31:80/sina/api/sessions

这样就实现了用 axios 进行 跨域转发 

且可以实现 当地址中不含 /sina 时正常请求,不进行转发

//axios 请求并 进行转发 -------------------------------------------------
//参数
var params=new URLSearchParams();
params.append('login',"admin");
params.append('password',"admin");
/**/
this.$axios.post('/sina/api/sessions', params)
    .then(response => {
        // 处理响应数据
        console.log(response.data);
        this.current_call_token= response.data.token;
        console.log(this.current_call_token);
    })
    .catch(error => {
        // 处理请求错误
        console.log(error);
    });

 

posted @ 2023-06-30 13:49  海乐学习  阅读(2465)  评论(0编辑  收藏  举报