'Uncaught SyntaxError: Unexpected token <' in Node.js 'Uncaught SyntaxError: Unexpected token <' in Node.js express express

'Uncaught SyntaxError: Unexpected token <' in Node.js


Usually when the browser requests a JavaScript file, the server sends an HTML file. This is due to rules like app.get('*'.... So we need to tell the server to send the static files first and then declare the rules, like shown below:

// Declare static folder to be served. It contains the JavaScript code, images, CSS, etc.app.use(express.static('build'));// Serve the index.html for all the other requests so that the// router in the JavaScript application can render the necessary componentsapp.get('*', function(req, res){  res.sendFile(path.join(__dirname + '/build/index.html'));  //__dirname : It will resolve to your project folder.});


My folder structure

node(folder)     server.js     -client(f)           -index.html           -views(f)           -js(f)              -ctrl(f)              -service(f)              -app.js              -state.js

and

app.use(express.static('client'));app.get('/index.html', function (req, res) {  res.sendfile(_dirname + '/index.html');});

Call this from the browser: http://127.0.0.1:1956/index.html

var server = app.listen(1956, function (req, res) {    var host = server.address().address    var port = server.address().port    console.log("app listening at", host, port)});

It's working fine for me.


I think this may be caused by your /public/index.html file.

When you include the JavaScript files in the index.html file, there's some problem with the "src" property. Thus it will return a "not found" HTML file instead of the actual JavaScript file.