Nextjs getInitialProps无法与NGINX一起使用

时间:2019-04-10 16:52:53

标签: reactjs docker nginx reverse-proxy next.js

所以我有一个Next.js React组件,它使用getInitialProps在初始页面加载之前调用一些数据的后端。看起来像这样:

 static async getInitialProps({req, query}){
    console.log('inside getInitialProps')
    if (req){
      var pinReturn = await axios.post(process.env.serverADD+'getPinData', {withCredentials: true})
      .then(response=>{
        console.log('value of response: ', response)
        return response.data.pins
      })
      .catch(error=>{
        console.log('value of error: ', error)
        return({})
      })

    }
    return {pinData: pinReturn}
  }

我认为这很容易解释-当我的后端是一个简单的docker容器时,它就可以工作。但是,现在我正在使用nginx和docker-compose旋转前端和后端。目前,我的process.env.serverADD等于http://localhost:80/back/

我的NGINX是:

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

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

    server_name example.com www.example.com localhost;

    location /back {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";

      proxy_pass http://nodejs:8000;
    }

    location / {
      proxy_pass http://nextjs:3000;
    }

    location ~ /.well-known/acme-challenge {
      allow all;
      root /var/www/html;
    }
}

这是我的docker-compose(类似于这里的https://www.digitalocean.com/community/tutorials/how-to-secure-a-containerized-node-js-application-with-nginx-let-s-encrypt-and-docker-compose#step-2-%E2%80%94-defining-the-web-server-configuration):

version: '3'

services:
  nodejs:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    container_name: nodejs
    restart: unless-stopped
    networks:
      - app-network
  nextjs:
    build:
      context: ../.
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    container_name: nextjs
    restart: unless-stopped
    networks:
      - app-network
  webserver:
    image: nginx:mainline-alpine
    container_name: webserver
    restart: unless-stopped
    ports:
      - "80:80"
    volumes:
      - web-root:/var/www/html
      - ./nginx-conf:/etc/nginx/conf.d
      - certbot-etc:/etc/letsencrypt
      - certbot-var:/var/lib/letsencrypt
    depends_on:
      - nodejs
      - nextjs
    networks:
      - app-network

volumes:
  certbot-etc:
  certbot-var:
  web-root:
    driver: local
    driver_opts:
      type: none
      device: /
      o: bind

networks:
  app-network:
    driver: bridge 

如果我从curl调用http://localhost:80/back/getPinData,那么我会得到期望的数据。它通过nginx路由,命中我的docker-compose,然后路由到我的nodejs应用程序中的正确位置。但是,如果我从getInitialProps调用该API,则会出现以下错误:

inside getInitialProps
value of error:  { Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 80,
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json;charset=utf-8',
        'User-Agent': 'axios/0.18.0',
        'Content-Length': 24 },
     method: 'post',
     url: 'http://localhost:80/back/getPinData',
     data: '{"withCredentials":true}' },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     _events:
      [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { maxRedirects: 21,
        maxBodyLength: 10485760,
        protocol: 'http:',
        path: '/back/getPinData',
        method: 'post',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'localhost',
        port: '80',
        nativeProtocols: [Object],
        pathname: '/back/getPinData' },
     _ended: false,
     _ending: true,
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 24,
     _requestBodyBuffers: [ [Object] ],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: false,
        _headerSent: true,
        socket: [Socket],
        connection: [Socket],
        _header:
         'POST /back/getPinData HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 24\r\nHost: localhost\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/back/getPinData',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'http://localhost:80/back/getPinData' },
response: undefined }

这是怎么回事?为什么不使用NGINX时getInitialProps似乎可以工作,但是使用反向代理时为什么会失败?

1 个答案:

答案 0 :(得分:2)

从容器中解析URL时,localhost不再是您的实际主机。而是容器本身的环回适配器。

如果您尝试从Docker容器中调用Nginx服务器,则需要使用http://webserver:80/back/getPinData

您已经将docker-compose.yml设置为使用bridge network,因此应该可以立即使用。