Ad

Configure Production Environment In A Create-react-app(SyntaxError: Unexpected Token < In JSON At Position 0)

I want to configure production environment in my app (using create-react-app). Maybe it's a silly question to ask because I'm searching and there are lots of articles about this but none of this helped me. Also, I used codes in create-react-app here(production) and here(development) but still not working.

For server side, I'm using node and all API are working well with development mode in react. but when I'm using production mode It's not working.

It's just returning

SyntaxError: Unexpected token < in JSON at position 0

in the browser console.

I can't access my routes in the server in production mode.

How can I solve it? Help appreciated.

This is my app tree, front-end folder includes my react code and running on a different port (server: 3000, react: production:3001, development:5000). I have added this lines of code to app.js :

app.use(express.static(path.join(__dirname, 'front-end/build')));
 app.get('*', function (req, res) {
 res.sendFile(path.join(__dirname, 'front-end/build', 'index.html'));
 });

and this in www.js:

if (process.env.NODE_ENV === 'production') {
app.use(express.static('front-end/build'));
 }

enter image description here

Ad

Answer

I found my answer and my app is working in production mode now, and I have deployed it. I just added this lines into my app.js in the root directory in server-side code(node application):

let root = path.join(__dirname, '..', 'myapp/fron-end/build');
  app.use(express.static(root));
  app.use(function(req, res, next) {
  if (req.method === 'GET' && req.accepts('html') && !req.is('json') && 
     !req.path.includes('.')) {
         res.sendFile('index.html', { root });
    } else next();
  });

Here myapp is the name of my project folder(server-side) and fron-end is the name of my front-end folder that includes builds folder that has created for production. (I put my front-end folder inside server-side folder)

This link helps me. Uncaught SyntaxError: Unexpected token < #1812

Hope this helps others.

Ad
source: stackoverflow.com
Ad