N
N
Nikita Shchypylov2018-09-16 14:34:42
Node.js
Nikita Shchypylov, 2018-09-16 14:34:42

Why am I getting "Uncaught SyntaxError: Unexpected token" when uploading an html file?

Hello!
Front on React, back Express.
If I set it like this, then everything works:

const buildPath = path.join(__dirname, "../../dist");
const buildIndexPath = path.join(__dirname, "../../dist/index.html");

app.use(express.static(buildPath));
app.get("*", (req, res) => {
  res.sendFile(buildIndexPath);
});

But if I swap .get() with .static then I get an error:
app.get("*", (req, res) => {
  res.sendFile(buildIndexPath);
});
app.use(express.static(buildPath));

Uncaught SyntaxError: Unexpected token <
Allegedly swears at !doctype.
Why is that?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-09-18
@Nikulio

The error is not when returning the html file. He gives up without a problem. In the second case, problems with static. express.static is middleware. Express processes all requests in order through all middleware until it finds a suitable endpoint. In the first case, express.static handles paths to the router, intercepting only requests for static files and returning files in response. In the second case, these requests go to the router, which processes all paths for you and returns index.html. Requests do not reach express.static and instead of all statics you get this file and the JS parser gives an error.
Simple example:

app.use((req, res, next) => {
  console.log('Time: ', Date.now());
  next();
});
app.use(express.static(__dirname + '/public'));
app.get("/about", (req, res) => { /* */}); // ( 1 )
app.get("/home", (req, res) => { /* */});  // ( 2 )
app.get("*", (req, res) => { /* */}); // ( 3 )
app.get("/never", (req, res) => { /* */}); // ( 4 )

Let's say 4 requests come in:
GET https://site/public/img/1.png
GET https://site/home
GET https://site/feed
GET https://site/never

In all cases, the console will show: Time: <текущее время>
The first request will be intercepted by express.static and will not reach the router.
The second request will be intercepted by the endpoint ( 2 ), ( 1 ) will be skipped because the paths do not match.
The third endpoint ( 3 ), since it intercepts absolutely all requests that reach it, ( 1 ) and ( 2 ) are skipped, respectively.
The fourth request will also be intercepted and processed by the endpoint ( 3 )
. Requests cannot reach the endpoint ( 4 ). It should be swapped with ( 3 )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question