erver.proxy作用是为开发服务器配置自定义代理规则。期望接收一个{ key: options }对象。如果 key 值以^开头,将会被解释为RegExp。configure可用于访问 proxy 实例。(--官网)
示例:
server: {
proxy: {
// 字符串简写方式
'/api': 'http://localhost:9000'
// 选项写法
'/api: {
// 所要代理的目标地址
target: 'http://localhost:9000',
// 重写要代理到远程服务器的path,比如在本地项目, baseUrl是 `/api/xxx`, 被重写之后就变成 `/xxx`,被重写之后的path也正是我们要代理到远程的接口路径
rewrite: path => path.replace(/^\/api/, ''),
changeOrigin: true, // true/false, Default: false - changes the origin of the host header to the target URL
}
}
}
前端接口调用:
fetch('/api/index') // 或使用 XmlHttpRequest
此时会通过上面的代理规则,将源地址 (本地地址) 代理到目标地址 (远程地址),从而访问目标地址的接口
最后,需要注意的是 /api
开头的 /
不能丢,正则匹配也是