Home > database >  Browser thinks that the HTML file is a js file
Browser thinks that the HTML file is a js file

Time:12-24

I am writing a website using NodeJS and Express. After specifying a link with 2 route parameters:

app.get('/game/:port/:player/', function(req, res) {
    res.sendFile(path.join(__dirname, '/game/game.html'));
})

-the result is a blank white page. Looking at DevTools, I saw the error Uncaught SyntaxError: Unexpected token '<' game.js:1. It looks like the browser is interpreting the html file as a JavaScript file! I think this is because the browser tries to fetch the js and css files from /game/(portnumber)/(playernumber) instead of from /game. And the css shows up as the actual HTML file:

enter image description here

However, another route that I have with only 1 route parameter works just fine! I am still relatively new to Express so I don't really understand how fetching directories works.

Is there any way to fix this directory error without manually specifying every single path in which there are HTML files?

CodePudding user response:

You can use the express.static middleware to specify a public directory your clients have access to:

https://expressjs.com/en/starter/static-files.html

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

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

CodePudding user response:

This doesn't really have anything to do with Express. It is basic URL resolution.

The browser will request /game/3561/2 and get an HTML document back

That document will tell it to load ./game.js which it will resolve to /game/3561/game.js (since a URL starting with a . means "resolve the path from current directory").

That isn't the URL of your JS file, so you get an HTML document instead — where :player is game.js.

You need to write the actual URL to your JS file in the src attribute.

  • Related