解决跨域——前端代理

仅能在开发环境下配合 webpack、vite、rollup 等前端构建打包工具使用。

注意:生产环境需要配合 nginx 代理

1
2
前端 5173端口
后端 3000端口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>跨域的四种解决办法</title>
</head>
<body>
<script>
// 2.build-up tools proxy
// fetch('http://localhost:5173/api/json')
// 本地
fetch('/api/json')
.then((res) => res.json())
.then((data) => {
console.log(data);
});
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3000/api',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});

解决跨域——前端代理
https://hugtyftg.github.io/2024/01/28/解决跨域——前端代理/
作者
mmy@hugtyftg
发布于
2024年1月28日
许可协议