简体   繁体   中英

Express.js and ejs directory of folder

I want to insert this image which is located here: images/image.png My main/start file is here: server.js my routes are here: routes/main.js my ejs file where I want to insert the image is here: views/main/index.ejs What directory do I have to use to get the image?

I tried to go from the ejs file: ../../images/image.png I tried to go from my routes: ../images/image.png And I tried to go from the main file ./images/image.png but nothing worked

<img src="../../images/image.png" alt="Cuold not load image">

https://i.stack.imgur.com/u0FFH.png

You haven't declared your "images" folder. Normally, javasript, CSS, images & etc are placed in a "public" folder. Add this codes to your server.js

const express = require("express");
const path = require("path");

const app = express();

app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));

Create "public" folder and place "img" / "images" folder in it.

在此处输入图像描述

Then in your index.ejs file. Add this codes to retrieve image.

<img src="/images/image.png" alt="your image">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM