我已经将我的代码简化为我可以做的最简单的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文件,并添加一个路由到它:

app.get('/css/MyCSS.css', function(req, res){
  res.sendFile(__dirname + '/public/css/MyCSS.css');
});

那么它似乎起作用了。

其他回答

我找到我的css文件,并添加一个路由到它:

app.get('/css/MyCSS.css', function(req, res){
  res.sendFile(__dirname + '/public/css/MyCSS.css');
});

那么它似乎起作用了。

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

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

服务静态文件(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">    

如果你的设置

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