简体   繁体   中英

How does app.use(express.static("public")) work with nested URL's?

I am quite new to node and I am trying to wrap my head around how the express.static middleware is working. In my views folder I have some href's like this:

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

My application is able to grab these files form URLS's such as localhost/about, localhost/contact etc. However it will not grab files if the end point is something like localhost/form/new. Is express.static getting these static assets from localhost/somefile and when there is a nested URL it defaults to /form/somefile (which won't work)? I am aware that if you put a '/' before vendor it will work from any level, why is this? Thank you.

app.use(express.static(“public”));

That is a way of saying "hey express, look if any incoming requests (like GET /bundle.css matches a file on that directory, if so, send it!".

Any file on that directory, you should be able to access under /. If you're serving from your localhost and have bundle.css on public folder, you can visit http://localhost/bundle.css .

Any asset you're trying to get from public folder, should start with / meaning look for an absolute path (in this case, the path public folder is serving which is /).

Update

There is another way of doing that using relative path which is not recommendable.

If you're in /about/index.html and you're trying to get /css/bundle.css (under public's folder)

Absolute Path:

<link rel="stylesheet" href="/css/bundle.css">

Relative Path: (not recommendable)

<link rel="stylesheet" href="../css/bundle.css">

The only thing to keep in mind is to make a slash mark before the static file address.


 <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="/css/style.css" type="text/css">


If you do not put this slash before the address, you will have a problem loading styles, images, etc. in the nested addresses.

For example, if you use the following addressing instead of the above operation, you will definitely have problems in the nested URL.

 <link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="css/style.css" type="text/css">


This is especially useful on page 404.

I hope it was useful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM