Skip to content
文档章节

正向代理

正向代理解决跨域在前端开发中表常见,其利用的是 nodejs 中的 http-proxy-middlewarenode-http-proxy 进行正向代理接口。

应用场景

webpack

js
module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: { '^/api': '' },
      },
    },
  },
};

vitejs

js
// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, ''),
      },
    },
  },
});

vue-cli

js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: '<url>',
        ws: true,
        changeOrigin: true,
      },
      '/foo': {
        target: '<other_url>',
      },
    },
  },
};

参考

  1. http-proxy-middleware
  2. node-http-proxy