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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐