Vite设置代理

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server: {
host: true,
port: Number(env.VITE_PORT),
open: true,
proxy: {
'/api': {
target: 'http://123.234.345.11:9999',
changeOrigin: true
// rewrite: (path) => {
// path.replace('/api', '');
// }
}
},
cors: true
},

官方

为开发服务器配置自定义代理规则。

期望接收一个 { key: options } 对象,如果 key 值以 ^ 开头,将会被解释为 RegExp。

configure 可用于访问 proxy 实例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
export default defineConfig({
server: {
proxy: {
// 字符串简写写法
'/foo': 'http://localhost:4567',
// 选项写法
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
// 正则表达式写法
'^/fallback/.*': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/fallback/, '')
},
// 使用 proxy 实例
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
configure: (proxy, options) => {
// proxy 是 'http-proxy' 的实例
}
},
// Proxying websockets or socket.io
'/socket.io': {
target: 'ws://localhost:3000',
ws: true
}
}
}
})

axios请求application/x-www-form-urlencoded格式

默认情况下,axios将JavaScript对象序列化为JSON。

要以application / x-www-form-urlencoded格式发送数据,使用qs库编码数据

安装

1
2
3
yarn add qs
# ts支持
yarn add @types/qs -D

使用

1
2
3
4
5
6
import QS from 'qs';

const params = QS.stringify({
name:'',
age:''
});

参考:axiosqs.parse()、qs.stringify()使用方法