Express中存在绝对路径和相对路径的困难

问题描述:

我在Express应用程序中有一条API路由,如下所示:

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/

但是,我想使用相对URL作为静态资源.例如,我希望到我的main.css的路线解析为:

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

相反,它当前解析为:

GET /username/bookmark/css/main.css

如何让我的应用将静态内容解析为/css/main.css并从URL中删除API的主要组件?

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?

我认为您应该使用express路由过程.

I think you should go with express routing process.

将以下行添加到您的app.js文件中

Add following line to your app.js file

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

将所有.css文件放入{approot}/public/stylesheets文件夹.

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

,并在您的HTML文件中添加如下链接

and in your HTML files add links like following

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