Code Guru
Code Guru

Reputation: 15598

node server is not serving static files

I have created a nodejs application using the express framework. I have used express.static to serve my static files.

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

There is a route that server the login.html.

// serve login page
app.get('/auth/login', loginPage);

and loginPage function

loginPage(req: any, res: any) {
   res.sendFile(path.join(__dirname, '..', '..', 'public', 'login.html'));
}

Now if I directly hit http://localhost:8080/login.html login page gets served with all its css and js files, so static files are getting served.

but when I hit http://localhost:8080/auth/login only login.html is served and the other css/js files showing 404 status.

If I check the request on browser network window request is for http://localhost:8080/auth/css/bootstrap.min.css, this is appending auth prefix.

but when I change URL mapping to /auth from /auth/login then it works fine.

How can I solve this?

Upvotes: 0

Views: 789

Answers (1)

Code Guru
Code Guru

Reputation: 15598

I was linking other js and CSS files without using / in href attribute. Like this

<link href="css/bootstrap.min.css" rel="stylesheet">

So I changed all the href by appending the /

<link href="/css/bootstrap.min.css" rel="stylesheet">

and now this is working. Thanks to @Patric

Upvotes: 2

Related Questions