Answer the question
In order to leave comments, you need to log in
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);
});
app.get("*", (req, res) => {
res.sendFile(buildIndexPath);
});
app.use(express.static(buildPath));
Answer the question
In order to leave comments, you need to log in
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 )
GET https://site/public/img/1.png
GET https://site/home
GET https://site/feed
GET https://site/never
Time: <текущее время>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question