ReactJS/Next.js:CRA 代理不适用于 Next.js(尝试将 API 请求路由到 Express 服务器)

ReactJS/Next.js: CRA Proxy Does Not Work With Next.js (Attempting To Route API Request To Express server)

我目前正在升级 vanilla React 应用程序以使用 Next.js(版本 7.0.0)。该应用程序最初是使用 Create-React-App 构建的,并利用 CRA 服务器内置的代理。

在开发中,我的 React 应用程序在 3000 端口 上运行,我有一个 Express 服务器 运行 在 5000 端口 上。在添加 Next.js 之前,我一直在 package.json 文件中使用 代理对象 来路由 API 向服务器请求。

API 请求:

const res = await axios.get('/api/request')

package.json中的代理对象:

"proxy": {
  "/api/*": {
    "target": "http://localhost:5000"
  }
}

这一直很好用,但是 Next.js 我现在收到一个错误:

GET http://localhost:3000/api/request 404 (Not Found)

^ 这应该指向 locahost:5000(我的服务器)

有谁知道我如何能够将 API 请求从 React/Next.js 客户端路由到不同端口上的 Express 服务器 运行?

好的,我已经弄明白了。您可以使用 http-proxy-middleware

为 Express 创建 Node.js 代理

然后您可以配置 target 选项以将请求代理到正确的域:

const proxy = require('http-proxy-middleware')

app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));