本文介绍了express.static()不能从不是"/"的路由器路径中的公用文件夹中提供文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Express.static配置:

Express.static config:

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

文件结构:

--public
  --assets
  --js
    --[js scripts]
  --stylesheets
    --[css files]

路线:

const shopRoutes = require('./routes/shopRoutes')
app.use('/', shopRoutes)

const itemApiRoutes = require('./routes/itemApiRoutes')
app.use('/api/shopitems', itemApiRoutes)

const logSignRoutes = require('./routes/logSignRoutes')
app.use('/account', logSignRoutes)

问题在于,根目录中"localhost:3000/"(shopRoutes)中的所有ejs文件都像这样调用以下css文件,并且运行良好:

The issue is that all ejs files in the root path at "localhost:3000/" (shopRoutes) calls for the following css file like so and works perfectly fine:

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

使用Express Router,路径"localhost:3000/account/login"处的ejs文件使用完全相同的语法调用相同的css文件,但会收到错误消息:

Using Express Router, the ejs file at the path "localhost:3000/account/login" calls for the same css file with the exact same syntax but gets the error:

Cannot GET /account/login/stylesheets/header.css/

我不理解express.static如何提供静态文件还是我做错了什么?

Am I not understanding how express.static serves static files or am I doing something incorrectly?

推荐答案

如果您指定相对网址,例如:

If you specify a relative URL such as:

href="stylesheets/header.css"

然后,浏览器将您所在网页的路径添加到其中,并从服务器请求合并的路径.除非您的网页位于网站的顶层并且没有路径,否则它将无法正常工作.我想强调的是,这是浏览器在做的,不是Express.因此,如果您使用的网址是以下网址:

then the browser adds the path of the web page you're in to that and requests that combined path from your server. Unless your web page is at the top level of your web site and thus has no path, it will not work properly. I want to emphasize, this is the browser doing this, not Express. So, if you're in a web page with this URL:

http://localhost:3000/account/login

而且,浏览器会看到:

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

最终将合并网页的路径

/account/login

< link> 标记中带有您的相对URL,并且您会发现,它会请求:

with the relative URL you in <link> tag and as you've found out, it will request:

/account/login/stylesheets/header.css

express.static()看到该URL时,它将与您的任何内容都不匹配

When, express.static() sees that URL, that will not match anything in your

__dirname + "/public"

目录层次结构,因此找不到它.

directory hierarchy so it will not be found.

相反,您想指定一个斜杠:

Instead, you want to specify a leading slash:

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

这告诉浏览器不要在URL上添加任何路径,它会向您的服务器发送以下请求:

That tells the browser not add any path to the URL and it will send a request to your server for:

/stylesheets/header.css

express.static()收到该请求时,会将其与

When express.static() gets that request, it combines that with

__dirname + "/public"

并最终会找到文件

__dirname + "/public" + "/stylesheets/header.css"`

将在您的公共目录层次结构中找到并且可以正常工作.

which will be found in your public directory hierarchy and will work.

这篇关于express.static()不能从不是"/"的路由器路径中的公用文件夹中提供文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:03