【问题标题】:React app with express server shows just blanc page带有快速服务器的 React 应用程序仅显示空白页面
【发布时间】:2020-10-26 21:44:40
【问题描述】:

我有一个没有路由的页面反应应用程序。它工作正常。现在我试图将它托管在 heroku 上,这就是我添加快递服务器的原因。我用'node server/server.js'运行服务器,之后我试图访问 http://localhost:3000 我只看到没有错误的空白页面。我尝试在 heroku 上运行应用程序,但得到了相同的结果。 在页面代码中,我只看到 div “root”,它是空的,但里面应该呈现 div “app”。

我的服务器

const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '../', 'public');
const port = process.env.PORT || 3000;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
    res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
    console.log('Server is up!');
});

我的 package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "homepage": "https://reaweapp.herokuapp.com/",
  "dependencies": {
    "@material-ui/core": "^4.11.0",
    "@material-ui/lab": "^4.0.0-alpha.56",
    "@material/textfield": "^5.1.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "express": "^4.17.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "node server/server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  "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"
    ]
  },
  "devDependencies": {
    "gh-pages": "^3.1.0"
  }
}

我的 index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.register();

【问题讨论】:

    标签: javascript node.js reactjs express package.json


    【解决方案1】:

    我认为您在“../”中有 1 个额外的点,并且需要指向构建的路径:

    const publicPath = path.join(__dirname, './','build');
    
    

    自己做的另一种方法是使用 serve 包

    npm i serve --save
    

    并将 package.json 中的脚本更改为

    "scripts": {
        "dev": "react-scripts start",
        "start": "serve -s build",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject",
        "heroku-postbuild": "npm run build"
      },
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 2020-11-29
      • 2015-08-04
      • 2021-01-12
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多