Proxy to backend with default Next.js dev server

题意:

使用默认的 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
      }
    ]
  }
}

See Next.js Docs Rewrites

请参考 Next.js 官方文档 - Rewrites

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值