1
votes

I've built a simple base application using Express and Create-React-App (http://myfirst-reactapp.herokuapp.com/). My project is split into two parts: one is the server (it has a package.json and an index.js file) and the other one is the client (which was created using npm create-react-app).

I am trying to redirect the users from the server side to the client side (For example localhost:5000/test will redirect to localhost:3000/test), but after deploying it to Heroku, I got the following error, and could not find an answer that solves the issue:

Uncaught SyntaxError: Unexpected token <

index.js

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

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

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

const PORT = process.env.PORT || 5000;
app.listen(PORT);

package.json (server)

{
  "name": "heroku_base",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "6.11.2",
    "npm": "3.10.10"
  },
  "scripts": {
    "start": "node index.js",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2"
  }
}
1
It looks like the main.js file isn't loading correctly. Instead of JS it's loading your root page it appears. - Brett DeWoody

1 Answers

1
votes

You are returning the index.html file for every request to the express server.

Try removing this code

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

Also, you should probably replace

app.use(express.static('/client/build')); 

With something like

app.use(express.static(path.join(__dirname, 'client/build')));