在 CRA 中,代理是一个 JSON 属性 - 例如:
"proxy" : "http://localhost:5001"
这将捕获所有 HTTP 请求并将它们转发到后端。
Vite也有类似的东西:
export default defineConfig(() => {
return {
build: {
outDir: 'build',
},
server: {
proxy: {
"/api":'http://localhost:5001',
}
},
plugins: [react()],
};
});
问题是您的请求必须有 /api 前缀才能使该代理正常工作。我找不到任何讨论通配符的文档。理想情况下,它会是类似
"/*" : 'http://localhost:5001'
但这似乎不起作用。
我不想要 /api 的原因是我们有很多作业、讲义等的代码存储库,它们都有不同的
/prefix
es。因此,一项作业将只有 /todo
和另一项 /api/trains
等。我们可能需要调整代码,以便一切都是 /api
,但希望减少工作量。
我尝试过
'/'
,'/*'
,'/*/*'
,'/**'
,'^.*'
据我所知,Vite 的文档并没有明确支持通配符进行代理。
一个潜在的解决方法可能涉及创建一个中间件函数来处理这些请求。您可以使用 Express(或其他适当的中间件工具)之类的东西来实现自定义逻辑,以拦截传入请求并根据某些条件将它们重定向到适当的后端,而不是仅仅依赖 Vite 的内置代理功能。
这是一个使用 Express 的概念示例:
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
// Proxy specific routes
app.use('/api', createProxyMiddleware({ target: 'http://localhost:5001', changeOrigin: true }));
// Handle other routes as needed
app.use((req, res) => {
// Your logic to redirect or handle other routes
// For instance, you might dynamically determine the target based on the incoming request
// Example:
if (req.url.startsWith('/todo')) {
return createProxyMiddleware({ target: 'http://localhost:5002', changeOrigin: true })(req, res);
}
// Handle other cases as necessary
});
// Start the server
app.listen(3000, () => {
console.log('Server running on port 3000');
});