简体   繁体   中英

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

I'm new to React. I want to deploy my react project to Heroku. To do that I implemented a simple express server. But nothing renders on my browser at localhost:3000 when I run the server with node server/server.js . Am I missing something obvious here?

My project structure:

我的项目结构

server.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')));
});

index.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>

There is no index.html in src . With create-react-app the file index.html it would be put into build when command npm run build is executed. It generates an index.html with urls to the JS/CSS dynamically injected. One option is you you could consider putting the React application into public , then target index.html of the build folder generated by npm run build :

// 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')));
});

Also you need to make sure you have static file serving set up for express:

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

static can also target multiple directories in case you don't want to nest your react project too deeply:

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

It's fairly common to have static assets in public such as images, but regardless of the structure you choose, you need to specify a path for static assets including the HTML, CSS, and JS generated by create-react-app build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM