我已经将我的代码简化为我可以做的最简单的express-js应用程序:

var express = require("express"),
    app = express.createServer();
app.use(express.static(__dirname + '/styles'));
app.listen(3001);

我的目录是这样的:

static_file.js
/styles
  default.css

然而,当我访问http://localhost:3001/styles/default.css时,我得到以下错误:

Cannot GET / styles /
default.css

我使用express 2.3.3和节点0.4.7。我做错了什么?


当前回答

试一试”。而不是__dirname + '/public'。 类似地,尝试process.cwd() + '/public'。

有时我们会丢失正在使用的目录,最好避免假设文件位于我们指定的位置。

类似地,避免假设在依赖关系的深度中,路径在每个级别上都以相同的方式解释。

其他回答

我在我的应用程序中使用引导CSS, JS和字体。我在应用程序的根目录中创建了一个名为asset的文件夹,并将所有这些文件夹放在其中。然后在服务器文件中添加以下一行:

app.use("/asset",express.static("asset"));

这一行使我能够从/asset路径前缀(例如:http://localhost:3000/asset/css/bootstrap.min.css)加载资产目录中的文件。

现在在视图中,我可以简单地包括CSS和JS如下:

<link href="/asset/css/bootstrap.min.css" rel="stylesheet">

试一试”。而不是__dirname + '/public'。 类似地,尝试process.cwd() + '/public'。

有时我们会丢失正在使用的目录,最好避免假设文件位于我们指定的位置。

类似地,避免假设在依赖关系的深度中,路径在每个级别上都以相同的方式解释。

我在用

app.use(express.static('public'))

当公共文件夹中没有名为index.html的文件时。

我在浏览器中得到以下错误:

“不能得到/”

当我将文件重命名为“index.html”时,它可以正常工作。

对我有用的是:

而不是写app.use(express。Static (__dirname + 'public/images'));在你的app.js中

简单的写 app.use (express.static('公共/图像'));

即删除路径中的根目录名。然后你可以在其他js文件中有效地使用静态路径,例如:

<img src="/images/misc/background.jpg">

希望这对你有所帮助。

试试http://localhost: 3001 / default。

要在请求URL中使用/styles,请使用:

app.use("/styles", express.static(__dirname + '/styles'));

请看本页上的例子:

//Serve static content for the app from the "public" directory in the application directory.

    // GET /style.css etc
    app.use(express.static(__dirname + '/public'));

// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".

    // GET /static/style.css etc.
    app.use('/static', express.static(__dirname + '/public'));