我试图遵循文档并创建
vite.config.js
,如下所示:
const config = {
outDir: '../wwwroot/',
proxy: {
// string shorthand
'/foo': 'http://localhost:4567',
// with options
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
};
export default config;
并尝试通过以下调用来测试它:
fetch('/foo');
fetch('/api/test/get');
我预计会有实际的请求,如
http://localhost:4567/foo
和http://jsonplaceholder.typicode.com/test/get
但他们都以我的开发服务器作为起源,如下所示:http://localhost:3000/foo
和http://localhost:3000/api/test/get
我是不是理解错了?代理应该如何工作?
我还在 Vite 存储库中创建了一个 issue,但它已关闭,我不明白结束评论。
结果需要将
secure
标志指定为 false,如下所示:
proxy: {
'/api': {
target: 'https://localhost:44305',
changeOrigin: true,
secure: false,
ws: true,
}
}
相关github问题
基于Vite配置,您需要通过
server -> proxy
内的vite.config.js
指定:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "https://your-remote-domain.com",
changeOrigin: true,
secure: false,
},
},
},
// some other configuration
})
对于调试,我强烈建议向代理添加事件侦听器,这样您就可以看到请求如何转换、是否到达目标服务器以及返回了什么。
proxy: {
'/api': {
target: 'https://localhost:44305',
changeOrigin: true,
secure: false,
ws: true,
configure: (proxy, _options) => {
proxy.on('error', (err, _req, _res) => {
console.log('proxy error', err);
});
proxy.on('proxyReq', (proxyReq, req, _res) => {
console.log('Sending Request to the Target:', req.method, req.url);
});
proxy.on('proxyRes', (proxyRes, req, _res) => {
console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
});
},
}
}
proxy
将是“http-proxy”的一个实例,
请参阅更多信息https://github.com/http-party/node-http-proxy#options
假设 https://localhost:44305 是后端,端口 3000 是前端。
我觉得 Vite 文档有点混乱。
当我设置
'/api' : {target: 'https://localhost:44305'}
时,它实际上重定向到http://localhost:44305/api for http://localhost:3000/api,而不是重定向到https://localhost:44305/。
因此,如果您使用 axios.get(),则应将后端服务器设置为 'axios.get('/api/something')',http://localhost:44305/api/something
希望这个技巧对你有帮助。
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
server: {
proxy: {
'/api':'http://localhost:5000',
},
},
plugins: [react()],
});
//这是唯一对我有用的方法,你不需要所有参数,如目标、安全,只需上面的代码就足以在你的 vite.config.js 文件中,并确保你提供本地主机/api 中服务器的端口号。