在 node.js/express 中使用 EJS 显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17755147/
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
Displaying an image with EJS in node.js/express
提问by gone
I'm just trying to get setup with node.js/express/ejs. I know ejs isn't actual HTML and so I'm having a hard time just displaying a simple image. Can someone point me in the right direction?
我只是想用 node.js/express/ejs 进行设置。我知道 ejs 不是真正的 HTML,所以我很难只显示一个简单的图像。有人可以指出我正确的方向吗?
Directory structure is:
目录结构为:
- myApp/server.js
- myApp/views/index.ejs
- myApp/logo.jpg
- 我的应用程序/server.js
- myApp/views/index.ejs
- 我的应用程序/徽标.jpg
Right now I have
现在我有
// index.ejs
<img src = "../logo.jpg" />
Am I going about this the wrong way? Thanks.
我会以错误的方式解决这个问题吗?谢谢。
回答by gustavohenke
Static files in Express must go inside the directory specified in your staticmiddleware. This is commonly ./public/.
Express 中的静态文件必须位于static中间件中指定的目录中。这是常见的./public/。
For example, in your server.jsyou may have something like this:
例如,在你的server.js你可能有这样的事情:
app.use( express.static( "public" ) );
Each file inside this folder will be accessible from the root URL, so this will work:
此文件夹中的每个文件都可以从根 URL 访问,因此这将起作用:
<img src="logo.jpg" />
回答by C. Khalifa
You have to assign app.use( express.static( "public" ) );on app.js then don't forget the / as root:
你必须app.use( express.static( "public" ) );在 app.js上赋值,然后不要忘记 / 作为 root:
<img src="/images/logo.jpg" />
the images folder should be in public folder:
图像文件夹应该在公共文件夹中:
- public/
- images/
- logo.png
- app.js
回答by Серик Касымбеков
My jsfile was here c:/blog/index.jsand image file c:/blog/views/image.js. And entered jsfile this code
我的js文件在这里c:/blog/index.js,图像文件c:/blog/views/image.js. 并输入js文件此代码
app.use( express.static( "views" ) );
app.use( express.static( "views" ) );
then in CSS added property
然后在 CSS 添加属性
body {
background-image: url("./image.jpg");
}
body {
background-image: url("./image.jpg");
}

