React + Express + Развертывание SQLite с Heroku дает 404 при Get = "/" - PullRequest
0 голосов
/ 30 мая 2020

Я пытаюсь развернуть create-react-app на Heroku с сервером Express, подключенным к базе данных SQLite. В разработке все работает нормально, однако в производстве создается следующий журнал, где method=GET path="/" возвращает 404.

2020-05-30T03:22:53.000000+00:00 app[api]: Build succeeded
2020-05-30T03:22:54.639920+00:00 heroku[web.1]: Starting process with command npm start
2020-05-30T03:22:57.641882+00:00 app[web.1]:
2020-05-30T03:22:57.641918+00:00 app[web.1]: > heroku-app@0.1.0 start /app
2020-05-30T03:22:57.641919+00:00 app[web.1]: > node server
2020-05-30T03:22:57.641919+00:00 app[web.1]:
2020-05-30T03:22:58.146414+00:00 app[web.1]: Node listening on port 15383
2020-05-30T03:22:58.147490+00:00 app[web.1]: Connected to material failures database
2020-05-30T03:22:58.697030+00:00 heroku[web.1]: State changed from starting to up
2020-05-30T03:23:25.514258+00:00 heroku[router]: at=info method=GET path="/" host=frozen-cliffs-13786.herokuapp.com request_id=24311843-65ba-49df-8464-195716354495 fwd="205.206.229.151" dyno=web.1 connect=1ms service=18ms status=404 bytes=493 protocol=https

Я вызываю маршрутизатор в react-ui/src/index.js

import 'react-app-polyfill/ie9';
import 'react-app-polyfill/stable';

// CSS
import './css/main.css';

import React    from 'react';
import ReactDOM from 'react-dom';
import Router from './components/router.component.js';

ReactDOM.render( <React.StrictMode> <Router /> </React.StrictMode>, document.getElementById( 'root' ) );

Моя структура папок выглядит следующим образом:

heroku-app
    react-ui
       node_modules
       public
       src
       .gitignore
       package-lock.json
       package.json
    server
    .gitignore
    app.json
    package.json
    package-lock.json
    static.json

Я честно перепробовал все, например:

  1. Добавление static.json
{
  "root": "react-ui/build/",
  "clean_urls": false,
  "routes": {
    "/**": "index.html"
  }
}
Добавление универсального сообщения в мой server/index.js файл. Я пробовал *, /* и /
const path        = require( 'path' );
const express     = require( 'express' );
const bodyParser  = require( 'body-parser' );
const compression = require( 'compression' );
const cors        = require( 'cors' );
const helmet      = require( 'helmet' );
const router      = require( './router.js' );

const PORT = process.env.PORT || 5000;
const app  = express();


app.use( cors() )
app.use( helmet() )
app.use( compression() )
app.use( bodyParser.urlencoded( { extended: false } ) )
app.use( bodyParser.json() )

app.use( '/api', router )

app.use( function ( err, req, res, next ) 
{
    console.error( err.stack )

    res.status( 500 ).send( 'Response 500: Server Error. Very Frustrating!' )
} )

app.use( function ( req, res, next ) 
{
    res.status( 404 ).send( 'Response 400: Page Not Found. Hmmmm...' )
} )

app.use( express.static( path.resolve( __dirname, '../react-ui/build' ) ) );

app.get( '*', function( request, response ) 
{
    response.sendFile( path.resolve( __dirname, '../react-ui/build', 'index.html' ) );
} );

app.listen( PORT, function () 
{
    console.error( `Node listening on port ${ PORT }` );
} );
Добавление homepage к двум файлам package.json. Я пробовал . и https://frozen-cliffs-13786.herokuapp.com/

In root ...

{
  "name": "heroku-app",
  "version": "0.1.0",
  "homepage":".",
  "description": "materials failure database web application",

  "engines": {
    "node": "10.x"
  },
  "scripts": {
    "start": "node server",
    "build": "cd react-ui && npm install && npm run build"
  },
  "cacheDirectories": [
    "node_modules",
    "react-ui/node_modules"
  ],
  "dependencies": {
    "body-parser": "^1.19.0",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "helmet": "^3.22.0",
    "sqlite3": "^4.2.0",
    "lodash": "^4.17.15"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/joleneborrelli-uofa/material-failures-database.git"
  },
  "keywords": [
    "node",
    "heroku",
    "create-react-app",
    "react"
  ],
  "license": "MIT",
  "devDependencies": {}
}

In response-ui .. .

{
  "name": "react-ui",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000",
  "homepage":".",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "lodash": "^4.17.15",
    "react": "^16.13.1",
    "react-app-polyfill": "^1.0.6",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}
Переключение между BrowserRouter и HashRouter, со свойством basename и без него в react-ui/src/components/router.component.js
import React    from 'react';
import Homepage from './homepage.component.js';
import Page     from './page.component.js';

// React Router
import 
{
  BrowserRouter,
  Switch,
  Route
} from "react-router-dom";


export default function Router()
{
    return (
        <BrowserRouter basename={`${process.env.PUBLIC_URL}/`}>
            <div>
                <Switch>
                    <Route exact path="/" component={ Homepage } />
                    <Route path="/:page/:id" exact component={ Page } />
                </Switch>
            </div>
        </BrowserRouter>
    );
};

Я могу скоро выдернуть волосы.

1 Ответ

0 голосов
/ 16 июня 2020

Я обнаружил, что проблема заключалась в том, что папка react-ui была собственным репозиторием git, что и происходит на этапе create-react-app.

Ответ был найден здесь в комментариях ...

«Обязательно удалите папку git (сгенерированную приложением Create React) в каталоге клиента. . Это позволит Heroku создать ваше приложение React и исправить ошибку «Not Found». "

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...