仅能在开发环境下配合 webpack、vite、rollup 等前端构建打包工具使用。
注意:生产环境需要配合 nginx 代理
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> 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
| import { defineConfig } from 'vite'; export default defineConfig({ server: { proxy: { '/api': { target: 'http://localhost:3000/api', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ''), }, }, }, });
|