简体   繁体   中英

Difficulty with absolute and relative paths in Express

I have a route for an API in an Express app that looks like this:

app.get('/:username/:bookmark/', function(req, res) {

  // do stuff

})

As expected, this route resolves to:

GET /username/bookmark/

However, I would like to use relative URLs for my static resources. For example, I would like the route to my main.css to resolve to:

GET /css/main.css

Instead, it currently resolve to:

GET /username/bookmark/css/main.css

How can I get my app to resolve static content to /css/main.css and remove the leading components of the API from the URL?

I think you should go with express routing process.

Add following line to your app.js file

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

put your all .css files in {approot}/public/stylesheets folder .

and in your HTML files add links like following

<link rel="stylesheet" type="text/css" href="/stylesheets/index.css">

solution source: https://github.com/mongo-express/mongo-express/pull/205

I try and it work, just add "/" before the link, example:

you are in localhost:8080/courses/ and your href is: href="style/style.css" you will lead to localhost:8080/courses/style/style.css.

solution is add"/" before, example: href="/style/style.css" it will start from root " localhost:8080/style/style.css"

这是一个具体的示例,以使用express.static()中间件在./public中提供文件的典型用例为例:

app.use(express.static(__dirname + '/public'));

If you're at /username/bookmark/ and you link the CSS like this

<link href="css/main.css" />

or this

<link href="./css/main.css" />

It will resolve to /username/bookmark/css/main.css . But you want to link in like this

<link href="/css/main.css" />

The problem is, that the .static -middleware only routes at the base path / instead of all routes you defined.

When using try:

app.get("/:username/:bookmark/", function(req, res) {});

With the : you do not state which path you get, but it will get all paths and you know what the path is if you type req.params.username or req.params.bookmark . If you want the path to /username/bookmark/ you must do this:

app.get("/username/bookmark/", function() {});
    //Do something
});

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