EJS shows red mark when trying to embed data - node.js

i have this node server with express which directs data to different files like .ejs files and it worked before but I dont know what I did and so that it doesnt work, it marks every ejs's "<" in red.
im using VS CODE.
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.send("Hello wassup");
});
app.get('/homepage/:name', function(req,res){
res.render('home', {fullname : req.params.name});
});
app.get('/profile/:name', function(req, res){
var data = {Dummytext: "hey yo wassup and all that yea imma be right here tho",
hobbies : ['baskeall','computing','drawing', 'Learning', 'Driving'] };
res.render('profile', {fullname: req.params.name, data:data});
});
app.listen(4000);
and i have for example this ejs file that doesnt work
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>bla</title>
<link rel="stylesheet" type="text/css" href="partials/nav.css">
</head>
<body>
<% include partials/nav.ejs %>
<div class="user-info">
<div class="user-about">
<div class="user-name"><span><%= fullname %></span></div>
<div class="user-info_">
<div class="userimg">
<img src="/YDSign.png" alt="User profile" draggable="false" />
</div>
<div class="user-speech"><p><%= data.Dummytext%></p></div>
</div>
</div>
<div class="user-button">
<button type="button" class="friendAdd">Add Friend</button>
<button type="button" class="friendBell">Bell</button>
</div>
<div class="user-hobbies">
<div class="hobbies-list">
<h1>Hobbies</h1>
<div class="Upscroll"><img src="/iconList/ArrowUp.png" draggable="false"/></div>
<ul>
<% data.hobbies.forEach(function(item){ %>
<li><a><%= item %></a><img src="iconList/Hobbies.png" class="ident" /></li>
<% }); %>
</ul>
<div class="Downscroll"><img src="/iconList/ArrowDown.png" draggable="false" /></div>
</div>
</div>
</div>

Everything is fine.
You just should install plugin EJS language support in VSCode.
Just click CTRL+SHIFT+X and then write ejs in the search bar after that install the first one.
That works for me.

Related

i want to incorporate Head and Body in handlebars (node.js)

i want to encorporate my head and my body on handlebars, but i dont know how,
i will give an example on how im using it '''
<link rel="stylesheet" href="/css/index.css">
<h1> test</h1>
'''
the handlebars'''
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/nome.css">
<title>Documen</title>
</head>
<body>
{{{body}}}
</body>
</html>
'''
with this code im passing that every element go to this {{{body}}} right?
and i want to pass a head too, how do i do that?
really sorry if the question is confuse, i really dont know how to explain better
Firstly You need install npm install express express-handlebars.
Here you have folder and file project structure:
app.js
const express = require("express");
const exphbs = require("express-handlebars");
const app = express();
const PORT = process.env.PORT || 3000;
// view engine setup
app.engine(
"hbs",
exphbs.engine({
defaultLayout: "main",
extname: ".hbs",
})
);
app.set("view engine", "hbs");
app.get("/", (req, res) => {
res.render("home");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.listen(PORT, () => {
console.log(`Node Server running on port: http://localhost:${PORT}`);
});
main.hbs
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
{{>header}}
<div class="container d-flex justify-content-center align-items-center flex-column" style="height: 800px;">
{{{body}}}
{{>mainContent}}
</div>
{{>footer}}
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
</body>
</html>
header.hbs
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about">about</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
mainContent.hbs
<h2>Hello World from Handlebars</h2>
<h3>Express</h3>
<h4>Bootstrap 5</h4>
footer.hbs
<footer>
<p class="text-center text-muted">© Copyright 2021 The Awesome Stuff</p>
</footer>
home.hbs
<h1>Home Page</h1>
about.hbs
<h1>About Page</h1>
Output:
"express": "^4.17.1","express-handlebars": "^6.0.2"

How do i get my mongodb dataset to display in an ejs file

Rebuilding a previous project and trying to learn node and CRUD functions with mongodb. i have a connection to my database and a separate server.js file with mongoose and express.
in server.js the server runs correctly im just not sure how to view my data on the page
here is my code:
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
mongoose.connect("mongodb connection string here");
const recipeSchema = {
title: String,
ingredients: Array,
instructions: String,
picture_link: String
}
const Recipe = mongoose.model('Recipe', recipeSchema);
app.use(express.static('public'));
app.get('/', function(req, res) {
res.render('index', {});
});
app.get('viewrecipes', function(req, res){
Recipe.find({}, function(err, recipes) {
res.render('viewrecipes', {
recipesList: recipes
})
})
});
app.listen(4000, function() {
console.log('server is running');
});
viewrecipes.ejs file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" type="text/css">
<title>Document</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light ">
<div class="container-fluid">
<a class="navbar-brand" href="/">Recipe Fix!</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav ">
<li class="nav-item">
<a class="nav-link" id="submit-recipe" href="#">Submit a Recipe</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/viewrecipes">View Recipes</a>
</li>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search for recipes" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</ul>
</div>
</div>
</nav>
<%recipesList.forEach(recipe => {%>
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title"><%= recipe.title %></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><%= recipe.ingredients %></li>
</ul>
<div class="card-body">
<%= recipe.instructions %>
</div>
</div>
<%})%>
<script src="core.js"></script>
<script src="server.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>

TypeError: Cannot read property of 'db' undefined

I am new coder and developing To-Do App. I want to connect my app to mongoDB Atlas database from VSC editor Terminal. I use Node.js (Express) and mongoDB Atlas. When I uninstall Node.js and start code from scratch, it works fine because code is all OK but next day when I get back to the same project and run it, it doesn`t work anymore. It shows up an error. You may check this terrible error here on this link: https://prnt.sc/u8paeg
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString ='mongodb+srv://akhtarayaz:SpreadLoveEverywhere#cluster0.yfwfa.mongodb.net/Users?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
db = client.db()
app.listen(3000)
if (err) {
throw err;
}
})
app.use(express.urlencoded({extended: false}))
app.get('/', function(req, res){
db.collection('accounts').find().toArray(function(err, accounts){
res.send(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple To-Do App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1 class="display-4 text-center py-1">To-Do App</h1>
<div class="jumbotron p-3 shadow-sm">
<form action="/create-account" method="POST">
<div class="d-flex align-items-center">
<input name="account" autofocus autocomplete="off" class="form-control mr-3" type="text" style="flex: 1;">
<button class="btn btn-primary">Add New Item</button>
</div>
</form>
</div>
<ul class="list-group pb-5">
${accounts.map(function(account){
return `<li class="list-group-item list-group-item-action d-flex align-items-center justify-content-between">
<span class="item-text">${account.text}</span>
<div>
<button class="edit-me btn btn-secondary btn-sm mr-1">Edit</button>
<button class="delete-me btn btn-danger btn-sm">Delete</button>
</div>
</li>`
}).join('')}
</ul>
</div>
</body>
</html>
`)
})
})
app.post('/create-account', function(req, res){
db.collection('accounts').insertOne({text: req.body.account}, function(){
res.redirect('/')
})
})

Dynamic Handlebars Master Template with Backend

used HBS as Template engine in my express app. This issue come when trying to display the title in dynamic page (details page).
My Controllers
exports.getProduct = (req, res, next) => {
var prodId = req.params.productId;
Product.findById(prodId)
.then(([product]) => {
res.render('shop/product-detail', {
product: product[0],
title: product.title
});
})
.catch(err => console.log(err));
};
My Layout
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>{{{ title }}}</title>
</head>
My View
<div class="container">
<div class="card-deck">
<div class="card">
<img src="{{product.imageUrl}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.title}}</h5>
<p class="card-text">{{product.description}}</p>
<p class="card-text"><small class="text-muted">Rp {{product.price}}</small></p>
<form action="/add-to-cart" method="POST">
<button type="submit" class="btn btn-outline-primary btn-block">Add to Cart</button>
<input type="hidden" name="productId" value="{{product.id}}">
</form>
</div>
</div>
</div>
</div>
In view the product title is working fine. But in the master template (layout) is not showing up.
server side : title: product[0].title
frontend side replace <title>{{{ title }}}</title> with
<title>{{ title }}</title>

ExpressJS route not working?

I am using express with hoganjs templating instead of jade.
When I try to access one of my routes, it wont work though...
In app.js, I have the following (relevant to the route):
var awesome = require('./routes/awesome.js');
app.use('/awesome', awesome);
In the routes/awesome.js file, I have the following:
var express = require('express');
var router = express.Router();
/* GET awesome page. */
router.get('/awesome', function(req, res, next) {
res.render('awesome', { title: "awesome", message: "awesome"});
});
module.exports = router;
And lastly, here is my awesome template (located in ./views/awesome.hjs).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<meta name="Author" content="{{author}}"/>
<link rel="shortcut icon" href="" />
<!-- Bootstrap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="jumbotron">
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}, here is your message: {{message}}</p>
</div>
</div>
</div>
</div>
</body>
</html>
I have basically the same code for the index route so why wont this one work too?
In awesome.js change the router path location to /
router.get('/', function(req, res, next) {
res.render('awesome', { title: "awesome", message: "awesome"});
});
Now localhost:3000/awesome should be available.
app.use('/awesome', ...) matches all the routes starting with awesome. Paths specified in router.get('/awesome', ...) acts as sub-paths. The path URL will be localhost:3000/awesome/awesome.

Resources