Difficulty with absolute and relative paths in Express

后端 未结 5 667
挽巷
挽巷 2021-01-24 17:59

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

相关标签:
5条回答
  • 2021-01-24 18:28

    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"

    0 讨论(0)
  • 2021-01-24 18:34

    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.

    0 讨论(0)
  • 2021-01-24 18:37

    Here's a concrete example, take the typical use-case of serving files in ./public using the express.static() middleware:

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

    0 讨论(0)
  • 2021-01-24 18:43

    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
    });
    
    0 讨论(0)
  • 2021-01-24 18:47

    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">
    
    0 讨论(0)
提交回复
热议问题