小编典典

Express-js无法获取我的静态文件,为什么?

node.js

我将代码简化为我可以做的最简单的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.3node 0.4.7。我究竟做错了什么?


阅读 235

收藏
2020-07-07

共1个答案

小编典典

尝试http://localhost:3001/default.css

/styles在您的请求URL中使用:

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'));
2020-07-07