Настройка NGINX с SSR React и Node Express - PullRequest
0 голосов
/ 17 февраля 2020

Я создаю проект React на стороне сервера с Node, и Express У меня проблемы с настройкой NGINX. В журнале ошибок указывалось rewrite or internal redirection cycle while internally redirecting to "/index.html"....

Я смог исправить эту проблему, добавив 404. Как и ожидалось, я больше не получаю 505, а вместо этого получаю 404 Не найдено. Так что теперь я предполагаю, что он не смог найти /index.html. Как мне исправить это, чтобы он возвращал веб-страницу?

app.get('/*', (req, res) => {
  const branch = matchRoutes(routes, req.url);

  const promises = branch.map(({ route, match }) => {
    return route.loadData ? route.loadData(match) : Promise.resolve(null);
  });

  Promise.all(promises).then((dataArray) => {
    const helmetContext = {};
    const context = { dataArray };
    const content = renderToString(
      <HelmetProvider context={helmetContext}>
        <StaticRouter location={req.url} context={context}>
          <App />
        </StaticRouter>
      </HelmetProvider>,
    );


    if (context.url) {
      return res.redirect(301, context.url);
    }

    if (context.status === 404) {
      res.status(404);
    }

    const { helmet } = helmetContext;
    return res.send(
      `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        ${helmet.title.toString()}
        ${helmet.meta.toString()}
        ${helmet.link.toString()}
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <meta name="theme-color" content="#333">
      </head>
      <body>
        <div id="root">${content}</div>
        <script>window.__ROUTE_DATA__ = ${serialize(dataArray)}</script>
      </body>
      </html>
      `,
    );
  });
});

Мой nginx.conf выглядит так:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        root    /aws-react-ssr/build;
        index index.html;
        try_files $uri $uri/ =404;
        }

    location /api/ {
                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_pass http://10.0.1.187: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;
    }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

...