我已经将我的代码简化为我可以做的最简单的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”时,它可以正常工作。

其他回答

服务静态文件(css,图像,js文件)只需两步:

将CSS文件的目录传递给内置中间件express.static Var express = require('express'); Var app = express(); /*public是我项目目录下的文件夹,包含三个文件夹 css,形象,js * / //css =>文件夹包含css文件 //image=>文件夹包含图片 //js =>文件夹包含javascript文件 app.use(表达。静态(公共/ css)); 要访问CSS文件或图像,只需输入url http://localhost:port/filename.css ex:http://localhost:8081/bootstrap.css

注意:链接CSS文件到HTML只需输入<link href="file_name.css" rel="stylesheet">

如果我写这段代码

var express = require('express');
var app = express();
app.use('/css',express.static( 'public/css'));

要访问静态文件,只需输入url:localhost:port/css/filename.css 例:http://localhost: 8081 / css / bootstrap.css

注意链接CSS文件与HTML只需添加下面的行

<link href="css/file_name.css" rel="stylesheet">    

在你的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文件必须相同。

提供__dirname的问题是__dirname返回当前文件的路径,而不是项目的文件。 此外,如果使用动态头文件,每个页面将在不同的路径中查找静态文件,这将不起作用。 对我来说,最好的方法是用__dirname代替process.cwd(),它总是将路径捐赠给项目文件。

app.use(express.static(process.cwd() + '/public'));

在你的项目中:

link rel="stylesheet" href="/styles/default.css"

参见:process.cwd()与__dirname之间的区别是什么?

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

除此之外,确保静态文件路径以/ (ex…/资产/ css)……在主目录(/main)之上的任何目录中提供静态文件