Requests for JS and CSS giving index.html instead

2019-09-13 19:47发布

问题:

I'm using Express and create-react-app.

My React app is a ways along, and now I'm trying to serve it from an Express server.

// server/app.js

const express = require('express');
const path = require('path');

const app = express();

// Serve static assets

app.use(express.static(path.resolve(__dirname, '..', 'build')));

// serve main file

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});


module.exports = app;

(My build directory is populated when I do npm run build.

I view the page in Chrome, and what happens when loading the page at localhost:3000 is the Console prints Uncaught SyntaxError: Unexpected Token <, and in the Sources tab it shows that the content of my CSS and JS files are simply the same as index.html: as in this image.

This seems like a recognizable issue, so hopefully someone has seen this before. I'm sort of stumped on where to even begin, especially because I was actually serving the app from Express successfully at first. Then this started happening, then it stopped after some random switching of git branches and reverting and replaying changes, and then it started happening again. So I'm not even sure what makes it happen or not happen.

回答1:

It appears that your app.use(express.static... call is failing, so instead all of the requests (including for the static assets) are being handled by the app.get('*', (req, res) => { part.

As you are intending to use this to serve a React app, I'd suggest taking inspiration from a boilerplate, "to see how it's done". I personally use NYTimes's kyt project and there's react-starter-kit too.



回答2:

Try the following code changes which are detailed from the express documentation - serving static files in express:

Replace

app.use(express.static(path.resolve(__dirname, '..', 'build')));

With

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

Remove

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});


回答3:

The problem was "homepage": ... in package.json.

When npm run build runs and there is a homepage URL in package.json that has a non-empty path (like a Github Pages URL like this, https://username.github.io/project_name, where "/project_name" is the path), it changes where it expects the files inside /build to be. The requests for my js and css were going to /project_name/static/... instead of /static/....

It even said in the log output of npm run build:

The project was built assuming it is hosted at /project_name/.
You can control this with the homepage field in your package.json.

On my localhost, it wasn't hosted at /project_name/, so the paths were off.