Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js, Unexpected token <

I have simple express server which looks like that:

Epxress application:

var express = require('express');
var compression = require('compression');
var path = require('path');
var cors = require('cors');
var router = express.Router();

var app = express();

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

app.enable('trust proxy');

app.use(compression());

app.get('*', function(req, res) {
    res.header('Cache-Control', "max-age=60, must-revalidate, private");
    res.sendFile( path.join(__dirname, 'index.html') );
});


var server = app.listen(process.env.PORT || 5000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(`Example app listening at http://%s:%s`, host, port);
});

And simple html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Router test</title>
</head>
<body>
    <div id="root"></div>
    <script src="bundle.js"></script>
</body>
</html>

Inside of bundle.js i have ReactJS application with client-side routing:

render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="about" component={About} />
            <Route path="about2" component={About2} />
            <Route path="about3" component={About3} />
            <Route path="*" component={NoMatch} />
        </Route>
        <Route path="*" component={NoMatch} />
    </Router>
), document.getElementById('root'));

Whenever i try to navigate to domain:port/ (this route is supported by router) everething is OK. But when i try to navigate to more complex URL, like domain:port///.. etc i got an error in browser:

bundle.js:1 Uncaught SyntaxError: Unexpected token <

looke like instead of send bundle.js from static server response with index.html and inside bundle.js there is html markup.

How can i fix this?

Thanks!

like image 595
Yafim Dziuko Avatar asked Aug 03 '16 12:08

Yafim Dziuko


2 Answers

There seems to be a loopback occuring, since the * rule is serving a index.html every time, and when bundle.js is not found, it will serve index.html instead, thus trying to parse < as javascript.

A sort of index-ception if you will...

like image 171
BlockChange Avatar answered Oct 05 '22 10:10

BlockChange


Step 1

Folder structure:

public

   -> index.html

   -> bundle.js

Step 2

Configure static path like this

app.use(express.static('public'))

Step 3

Ensure if it is properly configured .Go to browser and access your js file directly like

localhost:3000/bundle.js

If you see your javascript ...Hurrray. If not then fight with step 2 then check step 3

Step 4

use same path in script tag in ui like

<script src="/bundle.js" type="text/javascript"></script>
like image 20
vijay Avatar answered Oct 05 '22 11:10

vijay