账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Next.js如何设置反向代理
    41
    0

    1.尝试用server.js 中增加http-proxy-middleware,但是不起作用

    const express = require('express')
    const next = require('next')
    const proxyMiddleware = require('http-proxy-middleware')
    
    const port = parseInt(process.env.PORT, 10) || 3000
    const dev = process.env.NODE_ENV !== 'production'
    const app = next({ dir: '.', dev })
    const handle = app.getRequestHandler()
    
    app.prepare()
    .then(() => {
      const server = express()
    
      server.get('/', (req, res) => {
        return app.render(req, res, '/')
      })
    
      server.get('*', (req, res) => {
        return handle(req, res)
      })
    
      const proxyTable = {
        '/api': {
                target: 'https://xx.xxx.com/',
                secure: false,
                pathRewrite: {'^/api' : ''},
                changeOrigin: true
            }
      }
    
      // proxy api requests
      Object.keys(proxyTable).forEach(function (context) {
        var options = proxyTable[context]
        if (typeof options === 'string') {
          options = { target: options }
        }
        server.use(proxyMiddleware(context, options))
      })
    
      server.listen(port, (err) => {
        if (err) throw err
        console.log(`> Ready on http://localhost:${port}`)
      })
    })
    .catch((ex) => {
      console.error(ex.stack)
      process.exit(1)
    })
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 孤心一人行 普通会员 1楼

      在 Next.js 中,你可以使用 React Router 的代理功能来设置反向代理。以下是一个简单的步骤:

      1. 首先,你需要在你的 Next.js 项目中安装 react-router-domproxy 模块。如果你还没有安装,可以使用以下命令进行安装:

      npm install react-router-dom proxy

      1. 然后,你需要在你的 Next.js 项目中设置代理。在你的 pages/_app.js 文件中,你可以添加以下代码:

      ```javascript import { useRouter } from 'next/router';

      const router = useRouter();

      // 设置代理 router.config({ proxy: { target: 'http://localhost:3000', changeOrigin: true, pathRewrite: { '^/': '/api', }, }, }); ```

      这里,我们使用 useRouter 函数来获取路由器实例,然后使用 router.config 方法来设置代理。

      1. 最后,你需要在你的项目中运行服务器。你可以使用以下命令:

      npm run dev

      这时候,你的服务器将监听本地的 3000 端口,当有请求到来时,服务器将自动处理并转发请求到 http://localhost:3000/api

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部