Мое приложение React на heroku открывает домашнюю страницу, но не открывает другие страницы - PullRequest
0 голосов
/ 29 мая 2020

Мое приложение React нормально работает локально и развертывается на heroku. Однако на домашней странице любая ссылка на другую страницу показывает пустую страницу с надписью «не найдено». Других сообщений об ошибках нет.

Вот мой серверный пакет. json файл:

{
  "name": "portfolio-generator",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "engines": {
    "node": "12.16.x"
  },
  "dependencies": {
    "axios": "^0.19.2",
    "bootstrap": "^4.5.0",
    "concurrently": "^5.2.0",
    "express": "^4.17.1",
    "if-env": "^1.0.4",
    "mongoose": "^5.9.13",
    "nodemon": "^2.0.4",
    "react-bootstrap": "^1.0.1",
    "react-bootstrap-validation": "^0.1.11",
    "styled-components": "^5.1.0"
  },
  "devDependencies": {},
  "scripts": {
    "start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
    "start:prod": "node server.js",
    "start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
    "client": "cd client && npm run start",
    "build": "cd client && npm run build",
    "heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build",
    "seed": "node ./seeders/seed.js",
    "install": "cd client && npm install"
  },
  "repository": {
    "type": "git",
    "url": "git+https://https://github.com/...../jtsy.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://https://github.com/...../jtsy/issues"
  },
  "homepage": "https://https://github.com....../jtsy#readme"
}

Вот клиентский пакет. json:

{
  "name": "portfolio-generator",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:3001/",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "bootstrap": "^4.4.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-bootstrap-validation": "^0.1.11",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^0.88.2",
    "styled-components": "^5.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

сервер. js

const express = require("express");
import npm package mongoose, the ODM for mongo database
const mongoose = require("mongoose");
const routes = require("./routes");

const app = express();
// set the port for mongo connection to 3001 in development mode
const PORT = process.env.PORT || 3001;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

app.use(routes);

// Connect to the Mongo DB (portfolio_db)
mongoose.connect(
  process.env.MONGODB_URI || "mongodb://localhost/portfolio_db",
  {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
);


app.listen(PORT, () =>
  console.log(`?  ==> API Server now listening on PORT ${PORT}!`)
);

На основании некоторых исследований я добавил файл stati c. json:

{
  "root": "build/",
  "clean_urls": false,
  "routes": {
    "/**": "index.html"
  }
}

По умолчанию route в routes / index. js на стороне сервера:

....
router.use("*", (req, res) =>
  res.sendFile(path.join(__dirname, "../client/src/index.html"))
);

module.exports = router;

В приложении js (реагирующий верхний компонент) реагирующий маршрутизатор используется следующим образом:

...
     <Router>
        <Switch>
          <DevDataContext.Provider value={devDataProvider}>
            <SetupContext.Provider value={setupProvider}>
              {setup.initialized ? (
                <Route exact path="/" component={Home} />
              ) : (
                  <Route exact path="/" component={Signin} />
                )}
              <Route exact path="/contact" component={Contact} />
              <Route exact path="/about" component={About} />
              <Route exact path="/Developer" component={Developer} />
              <Route exact path="/Signin" component={Signin} />
            </SetupContext.Provider>
          </DevDataContext.Provider>
          <Route component={NoMatch} />
        </Switch>
      </Router>
   ...

При всем этом я зашел в тупик. Домашняя страница загружается и обновляется, но никуда не перенаправляется.

EDIT: путь к index. html неверен. Он находится в папке 'publi c' в 'client', поэтому в routes / index. js теперь он:

 router.use("*", (req, res) =>
      res.sendFile(path.join(__dirname, "../client/public/index.html"))
    );

Теперь все, что я получаю, - это пустой экран на heroku. страница. Я предполагаю, что моя проблема основана на том, как определены маршруты, но я до сих пор не могу ее понять.

Моя структура папок:

/projectname
  server.js
  package.json
  ...
 /client
    package.json
      /public
        index.html
        ...
      /src
        App.js
        index.js
        ...
          /components
          /pages
 /controllers
 /models
 /routes
    index.js (this is where the path to index.html is defined)
      /api
        index.js
        ...

РЕДАКТИРОВАТЬ # 2 РЕШЕНИЕ Сделано пару ключевых изменений в сервере. js. Самым важным было добавление пакета path (ошибка ладьи ie). Мне также пришлось поместить app.use (routes) перед кодом маршрута реакции по умолчанию, который теперь находится за пределами блока кода «производственного».

const path = require('path');
const express = require("express");
const mongoose = require("mongoose");
const routes = require("./routes");

const app = express();
// set the port for mongo connection to 3001 in development mode
const PORT = process.env.PORT || 3001;

// Configure body parsing for AJAX requests
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Serve up static assets
**if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}
app.use(routes);
app.get("*", function (req, res) {
  res.sendFile(path.join(__dirname, "./client/build/index.html"));
});**

// Connect to the Mongo DB (portfolio_db)
mongoose.connect(
  process.env.MONGODB_URI || "mongodb://localhost/portfolio_db",
  {
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
);

// Start the API server on port 3001
app.listen(PORT, () =>
  console.log(`?  ==> API Server now listening on PORT ${PORT}!`)
);

Я также удалил ссылку на маршрут реакции по умолчанию в /routes/index.js

1 Ответ

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

Решение найдено. 3 изменения в server. js. Добавлено:

const path = require('path')

Однозначно ладья ie ошибка, забыв об этом! Кроме того, исправлен код, чтобы вытащить маршрут реакции по умолчанию из «производственного» блока кода и поместить его ниже app.use (routes), например:

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}
app.use(routes);
app.get("*", function (req, res) {
  res.sendFile(path.join(__dirname, "./client/build/index.html"));
});

Я также удалил маршрут реакции по умолчанию из /routes/index.js.

...