expressjs и создать развертывание приложения для реагирования с помощью zeit сейчас

Мне удалось развернуть приложение Create-React-App и выразить серверную часть с помощью now.sh, но проблема в том, что он получает только домашний маршрут (я могу маршрутизировать до / примерно из дома, но при перезагрузке / обновлении страницы я получаю 404 ошибка). Я пробовал несколько конфигов. Пожалуйста, мне нужна помощь.

  "public": false,
  "version": 2,

  "builds": [
    {
      "src": "server/index.js",
      "use": "@now/node",
      "config": {
        "maxLambdaSize": "20mb"
      }
    },
    {
      "src": "package.json",
      "use": "@now/static-build",
      "config": {
        "distDir": "build"
      }
    }
  ],
  "routes": [
    {
      "src": "/api/(.*)",
      "dest": "/server/index.js"
    },
    {
      "src": "/(.*)",
      "dest": "/build/$1"
    }
  ]
}

0 ответов

Это похоже на проблему, описанную здесь - https://create-react-app.dev/docs/deployment/

Если вы используете маршрутизаторы, которые используют API истории HTML5 pushState под капотом (например, React Router с browserHistory), многие статические файловые серверы выйдут из строя. Например, если вы использовали React Router с маршрутом для /todos/42, сервер разработки будет правильно отвечать на localhost:3000/todos/42, а Express, обслуживающий производственную сборку, как указано выше, - нет. Это связано с тем, что при загрузке новой страницы для / todos / 42 сервер ищет файл build / todos / 42 и не находит его. Сервер должен быть настроен для ответа на запрос к /todos/42, обслуживая index.html. Например, мы можем изменить наш пример Express выше, чтобы он обслуживал index.html для любых неизвестных путей:

app.use(express.static(path.join(__dirname, 'build')));

-app.get('/', function (req, res) {
+app.get('/*', function (req, res) {
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });

Когда пользователи устанавливают ваше приложение на домашний экран своего устройства, в конфигурации по умолчанию будет создан ярлык для /index.html. Это может не работать для маршрутизаторов на стороне клиента, которые ожидают, что приложение будет обслуживаться из /. Отредактируйте манифест веб-приложения в public/manifest.json и измените start_url в соответствии с требуемой схемой URL-адресов, например:

"start_url": ".",

Это помогло, когда у меня было 404 с Zeit - https://itnext.io/fix-404-error-on-single-page-app-with-zeit-now-b35b8c9eb8fb -

In order to solve the 404 error message, we have to make sure that when a user goes to any URL which is not the root URL (e.g. http://www.myapp.com/something or http://www.myapp.com/dashboard/example) and they have never loaded our web app before, they are redirected to the root URL. Once they have loaded the root URL then they can be redirected back to the page they were trying to access and everyone is happy!

Step 1 - in your project's public folder make another package.json file -

{
  "name": "myapp-spa",
  "version": "1.0.0",
  "scripts": {
    "start": "serve --single --cache=60000"
  },
  "dependencies": {
    "serve": "latest"
  }
}

Step 2 - Configure the 404 page

Now that our files are being served, if a person goes to a non-root URL, the server will look for a 404.html file to send them instead. This is our chance to redirect them and take them to the index.html page. Put the 404.html file in the same public folder as the index file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>404 Not Found | My App</title>
</head>
<body>
  <script>
    (function redirect() {
      if (document && document.location) {
        document.location.replace(`/?redirect=${encodeURIComponent(document.location.pathname)}`);
      }
    }());
  </script>
</body>
</html> 

Step 3. - Prepare for deployments

Now that, we have our redirect code, all we have to do is add a deploy command to our original myapp/package.json (this is not the file we created earlier):

{
  "scripts": {
    ...    
    "deploy": "yarn run build && now ./build --name=myapp-spa",
    "start": "react-scripts start",
    "build": "react-scripts build",
    ...
  }
}

Sweet, now all we need to do is call yarn run deploy and our app should stop getting the 404 error pages.

Step 4: Clean up

In order to get back to the page we originally requested e.g. myapp.com/something we need to redirect the page to the?redirect parameter we set earlier in the tutorial. To do this, we need to install the query-string library to parse the parameter. Then you can include the following code into your app in a place that loads after your routing code loads.

const queryString = require('query-string');

...

const params = queryString.parse(document.location.search);
const redirect = params.redirect; // this would be "abcdefg" if the query was "?redirect=abcdefg"
if (document.location.pathname === '/' && redirect) {
  document.location.assign(`${document.location.origin}/${redirect}`);
}

It’s important that you do not redirect the user with the above code until after the routing code is cached in the browser. Once you’ve finished, your app should be working just as it should be.

В основном наклеил все это дело, но обязательно проверьте статью. По-видимому, есть еще одно возможное решение, которое стоит попробовать:

{
  ...
  "builds": [
    { "src": "build/**", "use": "@now/static" }
  ],
  "routes": [
    {
      "src": "/(.*)\\.(.*)",
      "dest": "/build/$1.$2"
    },
    {
      "src": "/",
      "dest": "/build/index.html"
    },
    {
      "src": "/(.*)",
      "status": 301, "headers": { "Location": "/" }
    }
  ]
Другие вопросы по тегам