使用默认 Next.js 开发服务器代理到后端 [英] Proxy to backend with default Next.js dev server

查看:39
本文介绍了使用默认 Next.js 开发服务器代理到后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,当我使用 create-react-app 制作应用程序时,我会有一个 setupProxy.js 文件来路由与此类似的 API 请求

Before, when I made apps with create-react-app, I would have a setupProxy.js file that would route API requests similar to this

const proxy = require('http-proxy-middleware');
module.exports = function(app) {
    app.use('/api',
        proxy({
            target: 'http://localhost:8000',
            changeOrigin: true,
        })
    );
};

但这似乎不适用于 next.js.当我做同样的事情时,我会遇到各种错误.

But that doesn't seem to work with next.js. When I do the same thing, I get various errors.

谷歌搜索解决方案,很多人说使用某种自定义服务器.但是我将如何使用默认的 nextjs 开发服务器完成像上面这样的代理?(当我的 package.json 中的 devnext dev 时,相当于 npm run dev.

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.

推荐答案

现在在配置中有一个官方功能:重写

There is now an official feature for this in the config: Rewrites

除了正常的路径重写,他们还可以将请求代理到另一个网络服务器

Besides normal path rewrites, they can also proxy requests to another webserver

next.config.js:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:8000/:path*' // Proxy to Backend
      }
    ]
  }
}

参见 Next.js 文档重写

这篇关于使用默认 Next.js 开发服务器代理到后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆