本文翻译自:Express-js can't GET my static files, why?
I've reduced my code to the simplest express-js app I could make: 我将代码简化为我可以做的最简单的express-js应用程序:
var express = require("express"),
app = express.createServer();
app.use(express.static(__dirname + '/styles'));
app.listen(3001);
My directory look like this: 我的目录如下所示:
static_file.js
/styles
default.css
Yet when I access http://localhost:3001/styles/default.css
I get the following error: 但是,当我访问http://localhost:3001/styles/default.css
,出现以下错误:
Cannot GET / styles /
default.css
I'm using express 2.3.3
and node 0.4.7
. 我正在使用express 2.3.3
和node 0.4.7
。 What am I doing wrong? 我究竟做错了什么?
#1楼
参考:https://stackoom.com/question/Or7Y/Express-js无法获取我的静态文件-为什么
#2楼
default.css
should be available at http://localhost:3001/default.css
default.css
应该位于http://localhost:3001/default.css
The styles
in app.use(express.static(__dirname + '/styles'));
的styles
在app.use(express.static(__dirname + '/styles'));
just tells express to look in the styles
directory for a static file to serve. 只是告诉express在styles
目录中查找要投放的静态文件。 It doesn't (confusingly) then form part of the path it is available on. 它不会(令人困惑地)形成可用路径的一部分。
#3楼
除了上述内容之外,请确保静态文件路径以/(例如/ assets / css)开头,以便在主目录(/ main)上方的任何目录中提供静态文件
#4楼
I have the same problem. 我也有同样的问题。 I have resolved the problem with following code: 我已使用以下代码解决了该问题:
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')));
Static request example: 静态请求示例:
http://pruebaexpress.lite.c9.io/js/socket.io.js
I need a more simple solution. 我需要一个更简单的解决方案。 Does it exist? 是否存在?
#5楼
I find my css file and add a route to it: 我找到我的css文件并为其添加路由:
app.get('/css/MyCSS.css', function(req, res){
res.sendFile(__dirname + '/public/css/MyCSS.css');
});
Then it seems to work. 然后它似乎起作用。
#6楼
In your server.js : 在您的server.js中:
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/public'));
You have declared express and app separately, create a folder named 'public' or as you like, and yet you can access to these folder. 您已经分别声明了express和app,创建了一个名为“ public”的文件夹,或者根据需要创建了一个文件夹,但是您仍然可以访问这些文件夹。 In your template src, you have added the relative path from /public (or the name of your folder destiny to static files). 在您的模板src中,您已经添加了/ public的相对路径(或将目的地的文件夹名称添加到静态文件中)。 Beware of the bars on the routes. 当心路线上的酒吧。