最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't display an image with EJS file in node.js - Stack Overflow

programmeradmin1浏览0评论

i'm new to node.js and my just playing with it to make a website. I want to display a picture on the website and that picture is in the same directory as my ejs file, but it does not show up.. Am i doing something wrong ? Thank you !

Backend code

const express = require('express')

//Init App
const app = express();

//Load view engine
app.set('view engine','ejs');

// Home route
app.get('/', function(req,res){
res.render('index.ejs');
});

app.listen(3000, function(){
console.log('Server started in port 3000...');
});

ejs file content:

<!DOCTYPE html>
<html>
<head>
  <title>Hello World!</title>
</head>
<body>
  <h1>Picture test</h1>
  <img src="/Users/aray/Documents/Projects/Node/views/test.jpg">
</body>
</html>

The project strcture is :

- Node
  - app.js
  - views
    - index.ejs
    - test.jpg

i'm new to node.js and my just playing with it to make a website. I want to display a picture on the website and that picture is in the same directory as my ejs file, but it does not show up.. Am i doing something wrong ? Thank you !

Backend code

const express = require('express')

//Init App
const app = express();

//Load view engine
app.set('view engine','ejs');

// Home route
app.get('/', function(req,res){
res.render('index.ejs');
});

app.listen(3000, function(){
console.log('Server started in port 3000...');
});

ejs file content:

<!DOCTYPE html>
<html>
<head>
  <title>Hello World!</title>
</head>
<body>
  <h1>Picture test</h1>
  <img src="/Users/aray/Documents/Projects/Node/views/test.jpg">
</body>
</html>

The project strcture is :

- Node
  - app.js
  - views
    - index.ejs
    - test.jpg
Share edited Dec 26, 2019 at 8:49 Holger Will 7,5361 gold badge34 silver badges40 bronze badges asked Dec 25, 2019 at 5:57 wengren11wengren11 432 silver badges7 bronze badges 2
  • Could you give directory structure of the project? – Milan Karunarathne Commented Dec 25, 2019 at 17:27
  • - app.js and the folder views are at the same level. Inside the views directory i have the index.ejs file and the test.jpg picture – wengren11 Commented Dec 26, 2019 at 8:25
Add a ment  | 

1 Answer 1

Reset to default 4

you have to put your images (and other assets) in separate folder and serve this folder with express.static:

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

- Node
  - app.js
  - views
    - index.ejs
  - public
    - test.jpg
<img src="test.jpg">

further information can be found in the express documentation: https://expressjs./en/starter/static-files.html

发布评论

评论列表(0)

  1. 暂无评论