Как просмотреть страницу индекса, используя e js -темблирование вместо использования express .stati c содержимого в node.js? - PullRequest
0 голосов
/ 03 апреля 2020

Я могу просмотреть мой генератор меню ресторана с HTML с

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

с этим express static method. Но что, если бы я хотел посмотреть index page с этим ejs-tempalting. Вот мой main.js код:

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}`);
});

У меня есть index.ejs в views folder, но, по слухам, вам не нужно указывать путь для ejs. Если я запускаю программу, ошибок нет, но страница также не отображается. Так что я был бы признателен, если бы вы могли направить меня на правильный путь, мне нужно routes? Controllers

1 Ответ

0 голосов
/ 03 апреля 2020

Если вы хотите обслуживать stati c файлы типа HTML, то то, что вы делаете, правильно. Но если вы хотите предоставить templating-engine как ejs браузеру, вам нужно установить зависимость с помощью следующей команды

npm i ejs

, и вам нужно импортировать в ваш main.js файл

const ejs = require('ejs');

Теперь вам нужно настроить view engine

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

в вашем файле main.js. Итак, теперь ваш main.js файл будет выглядеть как

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 внутри views папки с именем index.ejs

...