簡體   English   中英

為什么我的瀏覽器在運行 express server (React.js) 時顯示空白頁面?

[英]Why my browser shows blank page when I run express server (React.js)?

我是 React 的新手。 我想將我的 React 項目部署到 Heroku。 為此,我實現了一個簡單的快速服務器。 但是當我使用node server/server.js運行服務器時,我的瀏覽器在localhost:3000上沒有任何渲染。 我在這里遺漏了一些明顯的東西嗎?

我的項目結構:

我的項目結構

服務器.js:

const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

// create a GET route
app.get('/*', (req, res) => {
  res.send(res.sendFile(path.join(__dirname, '../src/index.html')));
});

索引.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

src沒有index.html 使用create-react-app文件index.html它將在命令npm run build執行時放入build 它生成一個index.html其中包含動態注入的 JS/CSS 的 url。 一種選擇是您可以考慮將 React 應用程序放入public ,然后定位由npm run build生成的build文件夾的index.html

// create a GET route
app.get('/*', (req, res) => {
  // update this path to match how you set up express to serve static and where your build is output to
  res.send(res.sendFile(path.join(__dirname, 'public', 'path', 'to', 'build', 'index.html')));
});

您還需要確保為 express 設置了靜態文件服務

app.use(express.static('public'))

static還可以針對多個目錄,以防您不想將 React 項目嵌套得太深:

app.use(express.static('public'))
app.use(express.static('build'))

這是相當常見的有在靜態資產public ,如圖像,但無論你選擇的結構,你需要指定靜態資產,包括HTML,CSS的路徑,和生成的JS create-react-app構建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM