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


当前回答

Default.css应该在http://localhost:3001/default.css上可用

app.use(express。Static (__dirname + '/styles'));只是告诉express在styles目录中查找要服务的静态文件。它不会(令人困惑地)构成它可用路径的一部分。

其他回答

在你的server.js中:

var express   =     require("express");
var app       =     express();
app.use(express.static(__dirname + '/public'));

你已经分别声明了express和app,创建一个名为“public”的文件夹或其他你喜欢的文件夹,但你可以访问这些文件夹。在模板src中,您已经添加了从/public的相对路径(或静态文件的文件夹destiny的名称)。当心路上的栏杆。

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

这对我来说很有用:

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

这为我工作,我尝试使用公共目录,但它不工作。 但在这种情况下,我们提供了访问目录中的整个静态文件,希望对您有所帮助!

Webpack让事情变得尴尬

作为对所有其他现有解决方案的补充:

首先:如果你将文件和目录的路径建立在cwd(当前工作目录)上,事情应该照常工作,因为cwd是你启动node(或npm start, yarn run等)时所在的文件夹。

然而……

如果你正在使用webpack, __dirname行为将非常不同,这取决于你的节点。__dirname设置和你的webpack版本:

In Webpack v4, the default behavior for __dirname is just /, as documented here. In this case, you usually want to add this to your config which makes it act like the default in v5, that is __filename and __dirname now behave as-is but for the output file: module.exports = { // ... node: { // generate actual output file information // see: https://webpack.js.org/configuration/node/#node__filename __dirname: false, __filename: false, } }; This has also been discussed here. In Webpack v5, per the documentation here, the default is already for __filename and __dirname to behave as-is but for the output file, thereby achieving the same result as the config change for v4.

例子

例如,让我们说:

需要添加静态公用文件夹 它位于你的输出文件夹(通常是dist)旁边,在dist文件夹中没有子文件夹,它可能是这样的

const ServerRoot = path.resolve(__dirname /** dist */, '..');
// ...
app.use(express.static(path.join(ServerRoot, 'public'))

(重要的是:再次强调,这是独立于你的源文件在哪里,只看你的输出文件在哪里!)

更高级的Webpack场景

如果在不同的输出目录中有多个入口点,事情会变得更复杂,因为同一文件的__dirname对于输出文件(即条目中的每个文件)可能是不同的,这取决于该源文件合并到的输出文件的位置,更糟糕的是,相同的源文件可能合并到多个不同的输出文件中。

你可能想要避免这种场景,或者,如果你不能避免它,使用Webpack来管理和注入正确的路径,可能是通过DefinePlugin或EnvironmentPlugin。