Search code examples
node.jsherokuroutescreate-react-appproduction

Uncaught SyntaxError: Unexpected token < for GET requests in production mode


I have deployed my program in Heroku(Node backend and React for frontend by create-react-app). It's working well for POST requests but for GET requests I'm receiving

Uncaught SyntaxError: Unexpected token <

I have this code in app.js for the absolute path for build folder in front-end folder:

let root = path.join(__dirname, 'front-end', 'build'); // (on Heroku ==>  
path.join(__dirname, 'front-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();
 });

project folder

How can I fix this part to work for GET request as well?

Thanks in advance for help.


Solution

  • I have found my answer to change add the header to my fetch request in front-end as well Because here I'm checking the

    req.method === 'GET'

    So I have added the header to the request:

    fetch('/alladmins', { 
         headers: {"Content-Type": "application/json",
                    "Accept" : "application/json"}
          })
        .then(data => data.json())
        .then((data) => { this.setState({ arrayOfAdmins: data });
      }
      , 
      function (error) {
        console.error("Error with fetching /alladmins url:", error);
      });
    

    And it's working now, kinda weird because GET should not need this header but it's working.