I have a very basic problem with Node.js/Express/Jade that's surprisingly hard to describe. In my node.js application I use the Express framework for routing of HTTP requests. I also use Jade templates as views, who themselves link to files (css, js etc.) inside a directory that I have declared as static through the app.use(express.static(__dirname + '/public')); command.

When I route requests to resources like /about or /contact everything works as expected. But I found that as soon as my resources have multiple 'levels' like so /about/me the same jade view would still render, but it ends up in the browser without CSS styling!

So my assumption is that the virtual directories represented by the resource levels screw up where jade thinks it must look for relative paths (in this case, where to find the public directory containing the static files).

I can't just prefix the paths inside the jade template since I have to use the same template for different resource types, so I need a solution that works for arbitrary resource levels.

Is there such a solution?

有帮助吗?

解决方案

I am guessing that your Jade template has something that looks like the following:

doctype html
  head
    link(rel="stylesheet", type="text/css", href="css/style.css")
    ...

The href for the stylesheet is a relative path, meaning your browser will look for the CSS file relative to the page it is currently on. For example:

  • http://example.com/abouthttp://example.com/css/style.css
  • http://example.com/about/companyhttp://example.com/about/css/style.css

You can change the href to an absolute path so the CSS file location will always be constant no matter what sub-directory you are in:

link(rel="stylesheet", type="text/css", href="/css/style.css")

The key change here is the forward slash at the beginning of the href, turning the relative path into an absolute one.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top