vue3 axios配置跨域

1.在vue.config.js中配置webpack
module.exports = defineConfig({
    
    
  transpileDependencies: true,
  configureWebpack: {
    
    
    devServer: {
    
    
      proxy: {
    
    
        "/api": {
    
    //捕获API的标志,如果API中有这个字符串,那么就开始匹配代理,
          target: "192.128.0.0/",//代理的api地址,就是要跨域的地址
          changeOrigin: true,// 这个参数可以让target参数是域名
          ws: true,//是否启用websockets,用不到可设为false
          pathRewrite: {
    
    //对路径匹配到的字符串重写
            "^/api": "",
          },
        },
      },
    },
  },

});

2.在main.js中设置axios
import axios from "axios";
const Vue = require("vue");
import App from "./App.vue";

//设置axios请求的地址默认是'/api',这样根据第一步中配置的会将/api替换为'192.128.0.0/'
axios.defaults.baseURL = "/api";

const app = Vue.createApp(App);

//将axios挂载到原型对象上,vue3相比vue2有所改变,vue2这样写:Vue.prototype.$http = axios
app.config.globalProperties.$http = axios;
3.使用axios
//可以直接使用this.$http
this.$http.post("user/getInfo").then((res) => {
    
    
   console.log(res);
}) .catch((res) => {
    
    
    console.log(res);
});
4.参考

webpack开发配置API代理解决跨域问题-devServer

猜你喜欢

转载自blog.csdn.net/weixin_67585820/article/details/123526861