最近在开发一个Next.js应用,开发环境需要将api转发到后端服务上。网上搜了一遍,发现都是使用http-proxy-middleware
转发的,一堆配置代码。。。不是吧不是吧,配置个接口转发这么麻烦的吗?最后发现,其实Next.js从v9.5开始就支持代理转发,叫做Rewrites
废话不多说,直接上代码吧:
const rewrites = () => {
return [
{
source: "/api/common",
destination: "http://localhost:7000/api/common",
},
];
};
const nextConfig = {
reactStrictMode: true,
rewrites,
}
module.exports = nextConfig
如果有多个接口,还能使用通配符,比如
const rewrites = () => {
return [
{
source: "/api/:slug*",
destination: "http://lbqhbox:7000/api/:slug*",
},
];
};