我已经将我的代码简化为我可以做的最简单的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。我做错了什么?


当前回答

我在用

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

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

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

“不能得到/”

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

其他回答

这对我来说很有用:

app.use('*/css',express.static('public/css'));
app.use('*/js',express.static('public/js'));
app.use('*/images',express.static('public/images'));

在你的nodejs文件中

const express = require('express');
const app = express();

app.use('/static', express.static('path_to_static_folder'));

你的哈巴狗档案里

...
script(type="text/javascript", src="static/your_javascript_filename")
...

注意“静态”这个词。nodejs文件和pug文件必须相同。

我只是尝试这个代码和工作

const exp = require('express');
const app = exp();

app.use(exp.static("public"));

和工作,

工作前(未工作):

const express = require('express');
const app = express();
app.use(express.static("public"));

试试

对我有用的是:

而不是写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'));