webpack代理配置与vite配置

1,090 阅读1分钟
//vue-cli3 里面需要新增 vue.config.js做配置
const url = 'http://192.168.0.1:8888' //例如我们的服务器端接口地址
module.exports = {
  devServer: {
    proxy: {
        '/api': {                // 这里最好加一个/,以免和我们的路由冲突了
            target: url,         // 服务器端接口地址
            ws: true,            //如果要代理 websockets,配置这个参数
            secure: false,       // 如果是https接口,需要配置这个参数
            changeOrigin: true,  //是否跨域
            pathRewrite:{'^/api':''}  //是否将 /api 替换为空
        }
    }
  }
};
//此时 你本地访问  localhost:8888/*****  
//实际连接后台的是 http://192.168.0.1:8888/****
// 如果不设置pathRewrite:{'^/api':''} 则实际连接的后台为http://192.168.0.1:8888/api/****
//如果设置pathRewrite:{'^/api':'search'} 则实际连接的后台为http://192.168.0.1:8888/search/****

//如果需要配置多个代理到同一个url可以这样写
devServer: {
    proxy: [{
      context: ['/auth', '/api'],
      target: url,
    }]
  }

以下是vite的配置

import { defineConfig } from "vite";
import path from "path";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    host: "0.0.0.0",
    port: 11065,
    open: true,
    https: true,
    cors: true,
    // 设置代理,根据项目实际情况配置
    proxy: {
      "/api": {
        target: url,
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace("/api/", "/"), //类比与webpack里面的pathRewrite
      },
    },
  }
  plugins: [vue()],
});