题意:
使用默认的 Next.js 开发服务器代理到后端。
问题背景:
Before, when I made apps with create-react-app, I would have a setupProxy.js
file that would route API requests similar to this
以前,当我使用 create-react-app 创建应用时,我会创建一个 setupProxy.js
文件,该文件的作用是将 API 请求路由到后端,其功能类似于这样的配置。
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/api',
proxy({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};
But that doesn't seem to work with next.js. When I do the same thing, I get various errors.
但在 Next.js 中,这种方法似乎行不通。当我尝试进行同样的配置时,会遇到各种各样的错误。
Googling a solution, a lot say to use a custom server of some kind. But how would I accomplish a proxy like above using the default nextjs dev server? (Equivalent of npm run dev
when dev
in my package.json is next dev
.
通过谷歌搜索解决方案时,很多建议是使用某种自定义服务器。但如何使用默认的 Next.js 开发服务器实现上述代理功能呢?(也就是在我的 package.json 中 dev
脚本为 next dev
,即使用 npm run dev
启动的情况下)。
问题解决:
There is now an official feature for this in the config: Rewrites
现在 Next.js 配置中已经有了官方支持的特性来实现这一功能,即 Rewrites(重写)。
Besides normal path rewrites, they can also proxy requests to another webserver
除了常规的路径重写功能外,Rewrites 还可以将请求代理到其他 Web 服务器。
next.config.js
:
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:8000/api/:path*' // Proxy to Backend
}
]
}
}