如何为反向代理nextjs服务器设置相对路径

时间:2019-12-11 14:42:57

标签: reactjs next.js

我有两个服务器A和B,它们都托管在AWS上。 A的规则说/v2//v2发送到B。很好服务器B是使用nginx和express的NextJs应用程序。

所有路由均以/v2/开头,因此/v2/foo显示了一个页面。该页面给出了200的响应,但没有给出资产。服务器B同时具有专用IP和公用IP,并且转到B<IP>/v2/foo的IP地址中,资产加载正常。从A<IP>/v2/foo到那里,资产没有加载,所以我认为是相对路径问题?

我已找到this example的设置setAssetPrefix的方法:

// server.js

 const express = require('express')
const compression = require('compression');
const next = require('next')
const bodyParser = require('body-parser')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()
  // Not sure what this does
  app.setAssetPrefix('/v2') //??
  server.use(compression())
  server.use(bodyParser.json())
  server.use(bodyParser.urlencoded({ extended: true }))

  server.get('/v2/foo', function(req, res) {
    app.render(req, res, '/v2/foo', {})
  })


  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log(`> Ready on ${process.env.HOST}`)
  })

})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

同时使用服务器B的私有和公共ip地址都可以,但是使用服务器A的url时,页面会显示样式,但没有样式。主页使用“ css in js”并且可以正常工作,但不能使用/v2/foo

import ../../master.scss

next.config.js:

const sass = require('@zeit/next-sass')
const css = require('@zeit/next-css')
const withPlugins = require("next-compose-plugins")

const nextConfig = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    });

    return config;
  }
}

//https://github.com/zeit/next-plugins/issues/266#issuecomment-474721942
module.exports = withPlugins([
  [sass],
  [css, { cssModules: false, url: false }]
], nextConfig);

nginx:

server {
        listen 80;
        listen [::]:80;

        root /var/www/v2/html/dist;
        #index index.html index.htm index.nginx-debian.html;

        server_name <public_IP> <private_IP> <server_A_domain>;

        location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        }
}

2 个答案:

答案 0 :(得分:0)

尝试通过向proxy_pass_request_headers on;块添加location来传递所有标头

答案 1 :(得分:0)

您可以创建自定义 Express.js 服务器:

server.js

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const env = process.env.NODE_ENV || 'development'
const dev = env !== 'production'
const app = next({
  dir: '.', // base directory where everything is, could move to src later
  dev,
})

const handle = app.getRequestHandler()

let server

app
  .prepare()
  .then(() => {
    server = express()

    // Set up the proxy.
    if (dev) {
      const { createProxyMiddleware } = require('http-proxy-middleware')
      server.use(
        '/api',
        createProxyMiddleware({
          target: 'https://api.staging.gocrypto.com/',
          changeOrigin: true,
          cookieDomainRewrite: 'localhost',
          logLevel: 'debug',
        })
      )
    }

    // Default catch-all handler to allow Next.js to handle all other routes
    server.all('*', (req, res) => handle(req, res))

    server.listen(port, err => {
      if (err) {
        throw err
      }
      console.log(`> Ready on port ${port} [${env}]`)
    })
  })
  .catch(err => {
    console.log('An error occurred, unable to start the server')
    console.log(err)
  })

不要忘记将您的 cookie(如果您正在使用会话)重写到本地主机:

cookieDomainRewrite: 'localhost'

然后在package.json中添加一个脚本:

"scripts": {
    "dev": "node devServer.js",
    "build": "next build",
    "start": "next start",
  },