Displaying an image with EJS in node.js/express

余生长醉 提交于 2019-12-01 14:46:40

问题


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?

Directory structure is:

  • myApp/server.js
  • myApp/views/index.ejs
  • myApp/logo.jpg

Right now I have

// index.ejs
<img src = "../logo.jpg" />

Am I going about this the wrong way? Thanks.


回答1:


Static files in Express must go inside the directory specified in your static middleware. This is commonly ./public/.

For example, in your server.js you may have something like this:

app.use( express.static( "public" ) );

Each file inside this folder will be accessible from the root URL, so this will work:

<img src="logo.jpg" />



回答2:


You have to assign app.use( express.static( "public" ) ); on app.js then don't forget the / as root:

<img src="/images/logo.jpg" />

the images folder should be in public folder:

- public/
  - images/
    - logo.png
- app.js


来源:https://stackoverflow.com/questions/17755147/displaying-an-image-with-ejs-in-node-js-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!