javascript 如何在 node.js 中使用 express 框架提供图像文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15379004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serve the image files using express framework in node.js?
提问by sachin
In my application im using express framework to serve the client side files.But while giving background image for the html element.Its showing failed to load given url.
在我的应用程序中,我使用快速框架来为客户端文件提供服务。但是在为 html 元素提供背景图像的同时。它的显示无法加载给定的 url。
var express = require('express')
, http = require('http');
var app = express();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
In public folder i have created javascripts,stylesheets,images folder.Now i'm getting javascripts and stylesheets.But i don't know how to access the image file.
在公共文件夹中,我创建了 javascripts、stylesheets、images 文件夹。现在我正在获取 javascripts 和样式表。但我不知道如何访问图像文件。
.logo {
background:url('localhost:8080\logo.jpg');//This image url not loading
float:left;
width:20px
height:20px;
}
回答by Nick Mitchinson
If your file directory is like
如果你的文件目录是这样的
/public
/stylesheets
/javascripts
/images
/logo.jpg
then your public access begins at the /public
directory. This means that in order to access the image, the address would be localhost:8080/images/logo.jpg
.
那么您的公共访问从/public
目录开始。这意味着为了访问图像,地址将是localhost:8080/images/logo.jpg
。
In summary, you had two problems.
总之,你有两个问题。
- Use a forward slash (
/
), not a backslash (\
) in your URLs - You missed including the
image
directory in the address
- 在 URL 中使用正斜杠 (
/
),而不是反斜杠 (\
) - 您错过了
image
在地址中包含目录
回答by Shane N
You are also listening on port 8000, but the image you are referencing has port 8080.
您也在侦听端口 8000,但您引用的图像具有端口 8080。