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


当前回答

我在我的应用程序中使用引导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">

其他回答

试试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'));

静态目录

检查上面的图像(静态目录)的目录结构

const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))


//  or

app.use("/", express.static(publicDirectoryPath))
app.use((req, res, next) => {
res.sendFile(path.join(publicDirectoryPath,'index.html'))

如果你的设置

myApp
  |
  |__ public
  |     |
  |     |__  stylesheets
  |     |     |
  |     |     |__ style.css
  |     |
  |     |___ img
  |           |
  |           |__ logo.png
  |
  |__ app.js

然后, 放入app。js

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

并引用你的style.css:(在一些.pug文件中):

link(rel='stylesheet', href='/static/stylesheets/style.css')

我在用

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

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

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

“不能得到/”

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

我也有同样的问题。我已经解决了以下代码的问题:

app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));

静态请求示例:

http://pruebaexpress.lite.c9.io/js/socket.io.js

我需要一个更简单的解决方案。它存在吗?