基础使用

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

现在,对 /api/users 的请求会将请求代理到 http://localhost:3000/api/users

pathRewrite: 重写路径

如果不希望传递/api,则需要重写路径:

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

secure: HTTPS配置

默认情况下,将不接受在 HTTPS 上运行且证书无效的后端服务器。 如果需要,可以这样修改配置:

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'https://other-server.example.com',
        secure: false,
      },
    },
  },
};

绕过代理

有时不想代理所有内容。 可以基于函数的返回值绕过代理。

在该功能中,可以访问请求,响应和代理选项。

  • 返回 null 或 undefined 以继续使用代理处理请求。
  • 返回 false 会为请求产生 404 错误。
  • 返回提供服务的路径,而不是继续代理请求。

例如。 对于浏览器请求,想要提供 HTML 页面,但是对于 API 请求,想要代理它。 可以执行以下操作:

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        bypass: function (req, res, proxyOptions) {
          if (req.headers.accept.indexOf('html') !== -1) {
            console.log('Skipping proxy for browser request.');
            return '/index.html';
          }
        },
      },
    },
  },
};

多路径代理到同一目标

如果想将多个特定路径代理到同一目标,则可以使用一个或多个带有 context 属性的对象的数组:

module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['/auth', '/api'],
        target: 'http://localhost:3000',
      },
    ],
  },
};

启用根代理

请注意,默认情况下不会代理对 root 的请求。 要启用根代理,应将 devMiddleware.index 选项指定为虚假值:

module.exports = {
  //...
  devServer: {
    devMiddleware: {
      index: false, // specify to enable root proxying
    },
    proxy: {
      context: () => true,
      target: 'http://localhost:1234',
    },
  },
};

changeOrigin: 隐藏主机来源(解决跨域)

默认情况下,代理时会保留主机头的来源,可以将 changeOrigin 设置为 true 以覆盖此行为。 在某些情况下,例如使用 name-based virtual hosted sites,它很有用。

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    },
  },
};