1

Hi i am developing small application using react create app with node in thatis application i want to acess static file in node i use like this

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

but i am getting getting error

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Venkateswararao
  • 343
  • 1
  • 5
  • 19

1 Answers1

2

This is because you are serving the same file for every request - also for the scripts required by the original HTML page. The browser request script, it gets HTML and the parser fails on < of <doctype> or <html>.

You can see in the Network tab of your browser's developer console all of the requests that your browser is making - I can bet that you're requesting something like script.js and instead of JavaScript contents you get the HTML contents of your index.html file.

It seems that you're using Express. Use express.static to serve static files instead of res.sendFile()

Since it seems that you have every static file in build, use something like this:

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

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

app.use(express.static(dir));

app.listen(3000, function () {
  console.log('Listening on http://localhost:3000/');
});

This is the entire program that you need. Of course you can change the port number.

It will serve your index.html correctly but it will also serve all of the other assets like images, client-side scripts required with <script>, CSS files etc. plus also other HTML files if there are any.

If you don't want to use Express then see this answer for more options of serving files:

rsp
  • 107,747
  • 29
  • 201
  • 177
  • If I used app.use(express.static(dir)) it is working fine for Home page(http://localhost:3000/) and Admin (http://localhost:3000/admin) but i deploy in server it works for Home page when i move to admin page it through 502 Bad Gateway in server i used nginx – Venkateswararao Jun 13 '17 at 12:57