简体   繁体   中英

How to view index page using ejs-templating rather than using express.static content in node.js?

I can view my restaurant food menu generator with HTML with

app.get('/', function (req, res) {
res.sendFile(__dirname + '/views/index.html');});

with this express static method . But what if I wanted to view the index page with this ejs-tempalting . Here is my main.js code:

const bodyParser = require("body-parser");
var homeController = require("./Controllers/homeController.js");
var path = require("path");
const port = 3000,

express = require("express"),

app = express();
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, 'public')));
app.get('/function.js',function(req,res){ res.sendFile(path.join(__dirname + '/javascript/function.js')); });
app.get('/main.css',function(req,res){ res.sendFile(path.join(__dirname + '/css/main.css')); });
app.get('/', function (req, res) {
});
//should this view the index page?//
app.get('/', function(req, res) {
    res.render('index');
});

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(port, () => {

 console.log(`The Express.js server has started and is listening
➥ on port number: ${port}`);
});

I have the index.ejs in views folder but rumor says that you don't have to specify the path for the ejs . If I start the program, there are no errors but the page doesn't show either. So I'd appreciate if you can direct me to the right path, do I need routes ? Controllers ?

If you want to serve static files like HTML then What you are doing is correct. But if you want to serve templating-engine like ejs to the browser then you need to install dependency with below command

npm i ejs

and you need to import in your main.js file

const ejs = require('ejs');

Now, you need to setup view engine

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

in your main.js file. So, now your main.js file will look like

const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
var homeController = require("./Controllers/homeController.js");
var path = require("path");

const app = express();
const port = 3000,

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

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

//this is used if you want to serve HTML file
//app.use(express.static(path.join(__dirname, 'public')));

//should this view the index page?//
app.get('/', function(req, res) {
res.render('index');
});

app.listen(port, () => {
console.log(`The Express.js server has started and is listening
➥ on port number: ${port}`);
});

save file inside views folder with name index.ejs

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