使用express.static后静态文件路径规则的困惑求解
核心原因在于你配置的express.static("public")——这个中间件把backend/public文件夹设置成了服务器静态资源的根目录。浏览器请求静态资源时,Express会自动在public目录下匹配查找,完全和你的EJS文件所在的物理位置无关。下面逐个拆解你的路径问题:
能生效的路径
<link rel="stylesheet" href="/styles/shared.css" />
开头的/是服务器根路径(比如http://localhost:3000/)的绝对路径。服务器收到请求后,会直接去public/styles/shared.css查找,刚好匹配文件位置,所以生效。这是最稳妥的写法,不受页面URL层级影响。<link rel="stylesheet" href="styles/shared.css" />
这是相对路径,但它的基准是当前页面的URL,不是head.ejs的物理位置。比如你的页面URL是http://localhost:3000/,相对路径会解析成http://localhost:3000/styles/shared.css,服务器依然去public目录找这个路径,所以能生效。但如果页面URL是http://localhost:3000/posts/detail,这个路径会变成http://localhost:3000/posts/styles/shared.css,这时候服务器就找不到文件了——你可以测试这个场景验证。<link rel="stylesheet" href="../../styles/shared.css" />
同样基于当前页面URL解析。假设页面URL是http://localhost:3000/posts/detail,../../会往上跳两级,解析成http://localhost:3000/styles/shared.css,服务器能找到对应文件。但如果页面URL层级更深(比如/a/b/c),这个路径会解析成/a/styles/shared.css,就会失效。
无法生效的路径
<link rel="stylesheet" href="/public/styles/shared.css" />
绝对路径会让服务器去public/public/styles/shared.css查找(因为静态根是public),但你的项目里没有这个嵌套的public文件夹,所以找不到文件。<link rel="stylesheet" href="public/styles/shared.css" />
相对路径解析后是当前页面URL/public/styles/shared.css,服务器同样会去public/public/styles/shared.css查找,路径不存在,所以失效。<link rel="stylesheet" href="../../public/styles/shared.css" />
解析后是当前页面URL的上级上级/public/styles/shared.css,服务器还是会去public/public/styles/shared.css找,自然找不到文件。
最佳实践
推荐始终使用开头带/的绝对路径(比如/styles/shared.css),不管当前页面的URL层级如何变化,都能稳定指向静态资源,避免路径解析出错。
内容的提问来源于stack exchange,提问作者Eslam Salem

