how to solve Cannot read property 'name' of undefined in express js? - javascript

I'm not able to perform the routing with the parameter, I'm getting the error cant read property 'name'. I used the template engine twig.
Here is my template,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{About}}</title>
</head>
<body>
<P><h1>{{user}}</h1></P>
<P><h2>{{text}}</h2></P>
</body>
</html>
this is my main 'js' file-
const express=require('express')
const app=express()
app.use('./static',express.static('twig templet'))
app.set('view engine', 'twig')
app.set('views','./twig templet/views')
app.get('/',(res,req)=>{
req.render('index',{title:'EXPRESS',gred:'Hello-welcome to Express',mes:'This is twig file'})
})
app.get('/about/:name',(res,req)=>{
res.render('about',{About:'User',user:req.params.name,text:'This is twig file'})
console.log('user is:'+ req.params.name)
})
app.get('/calculation/:a-:b',(res,req)=>{
res.render('calculator',
{About1:'Calculation',
add:parseInt(req.params.a) + parseInt(req.params.b),
sub:parseInt(req.params.a) - parseInt(req.params.b),
mul:parseInt(req.params.a) * parseInt(req.params.b),
div:parseInt(req.params.a) / parseInt(req.params.b)})
//console.log('user is:'+ res.params.Name)
})
app.listen(5000,()=>{
console.log("server is running at 5000")
})

You have the callback values from the app.get() in the wrong order, it should be like this, you can omit the next though,
app.get('/about/:name',(req, res, next) => {}
That's it.

Related

i am trying to render an ejs file and the page keeps loading for hours

app.get('/all-datas', (req, res) => {
data.find({}, function (err, names) {
res.render('EJS.ejs', {
nameList: Uname
})
})
})
I want this code to be used in my javaScript but when http://localhost:5000/all-datas is accessed this the page does not render and keeps loading and loading
or just tell me the any other way
I have installed all required modules
tried changing the port
done lots and lots changes still i cant help
I also had the same problem. The cause of the problem in my case was that I was not redirecting when handling post request.
app.js
const express=require("express")
const bodyparser=require("body-parser")
const path=require("path")
const app=express()
app.set("view engine", "ejs")
app.set("views", path.join(__dirname, "views"))
app.use(bodyparser.urlencoded({extended:true}))
const list=[]
app.get("/", (req, res)=>{
const day=new Date()
const options={
weekday:"long",
day:"numeric",
month:"long"
}
const today=day.toLocaleDateString("en-US", options)
res.render("list.ejs", {day:today, list:list})
})
app.post("/", (req, res)=>{
const task=req.body.newItem
list.push(task)
res.redirect("/")
})
app.listen(3000)
list.ejs
<!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">
<title>Document</title>
</head>
<body>
<h1><%=day%></h1>
<h2>To Do List</h2>
<ul style="list-style-type: none; margin:0; padding: 0;">
<%for(let i=0; i<list.length; i++){%>
<li><%=list[i]%></li>
<%}%>
</ul>
<form action="/" method="post">
<input type="text" name="newItem">
<input type="submit" value="Add">
</form>
</body>
</html>
First of all, you don't need to specify the extension on '.ejs' on render. you are also not using the 'names" parameter inside the callback function. if you want to take 'Uname' from 'names'( Output docs of the query ), you can pass the whole array to ejs and take "uname" from there by using a loop (ex: forEach Loop).
To render all usernames form the Namelist
app.get('/all-datas', (req, res) => {
data.find({}, function (err, names) {
res.render('EJS', {
nameList: names
})
})
})
on Ejs :
<% nameList.ForEach((item)=>{ %>
<p> username: <%= item.Uname %> </p>
<% }) %>
If This doesn't work, Make sure you have written the loop on the Ejs file correctly.

<link> and <script> paths not working (Nodejs ejs MVC) [duplicate]

This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 7 months ago.
I have a problem with the paths of my <link> and <script scr>.
I am trying to respect an MVC structure and I have the header.ejs file included in home_view.ejs. But it does not work.
Even putting the paths absolute (which is orible I know) it doesn't work.
Here is my MVC structure :
home_view.ejs :
<%- include('header.ejs'); %>
blablabla
<%- include('footer.ejs'); %>
header.ejs :
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="./style/test.css"> <!-- not working -->
<title><%= titre %></title>
</head>
<body>
<header>
header
</header>
<main>
home_controller.js :
'use strict';
let titre = 'Bonjour Nicolas';
const homeView = (req, res) => {
res.render("home_view", { titre : titre });
}
module.exports = { homeView };
Thanks in advance for those who will answer me.
Edit :
My index.js :
'use strict';
/* eslint-env node, es6 */
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
const PORT = process.env.PORT || 4242;
app.use('/', require('./routes/home_route'));
app.listen(PORT, () => {
console.log(`serveur démaré: localhost:${PORT}`);
});
okay so your problem is you have not registered the static path for style sheets , so i would recommend you to put the style folder outside the views folder and then registere it in your index.js file as the mentioned in the comment:
app.use("/style",express.static(__dirname + '/style'));
this should work then.
The same needs to be done for your scripts
app.use("/script",express.static(__dirname + '/script'));

Exported functions are not defined. Parcel/Browserify

When I use a bundler to make my JS browser compatible my exported functions are not exported.
Error: (index):11 Uncaught TypeError: connect is not a function
at HTMLButtonElement.onclick ((index):11:46)
index.js (Same root file as index.html)
const {ethers} = require("ethers");
async function connect() {
if (typeof window.ethereum !== 'undefined') {
await ethereum.request({method: "eth_requestAccounts"});
}
}
module.exports = {
connect
}
index.html (Same root file as index.js)
<!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>HTML 5 Boilerplate</title>
<script src="./index.js" type="module"></script>
</head>
<body>
<button id="connect" onclick="connect()"> Connect </button>
</body>
</html>
Using parcel, which auto creates a dist file and starts a local server.
Also tried browserify and had same issue.
Parcel supports script tag/elements of type module.
This code works for me but window.ethereum is undefined, it's related to MetaMask no?
index.html
<!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>HTML 5 Boilerplate</title>
</head>
<body>
<button id="connect">Connect</button>
<script type="module">
//Import your module
import something from "./index.js";
//Assign event listener to button
document
.getElementById("connect")
.addEventListener("click", function (event) {
something.connect();
});
console.log("something", something);
/* JavaScript module code here */
</script>
</body>
</html>
index.js
const { ethers } = require("ethers");
async function connect() {
console.log("Inside connect function");
console.log("window.etherum", window.ethereum);
console.log("ethers", ethers);
if (typeof window.ethereum !== "undefined") {
await ethereum.request({ method: "eth_requestAccounts" });
}
}
module.exports = {
connect,
};

Serverless.yml AWS Lambda Embedding EJS Template body parameters into handler.js

I'm trying to embed an EJS template named 'ui.ejs' into handler.js.
The aim is to capture URL query parameters, then pass them to a function name 'ui.js' to capture data, that data is then passed onto the EJS UI template called 'ui.ejs'.
The script works just fine, but the actual web page looks scrumbled and wierd.
The actual web page UI looks something like this.
"\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n \r\n \r\n \r\n"
\r\n\r\n Next Page -> \r\n\r\n
\r\n\r\n <- Previous Page \r\n\r\n
Is it a problem with the stringify parsing?
Thanks in advance..!
Here's the handler.js code:
import {ui} from './index.js';
var ejs = require('ejs');
var fs = require('fs');
const path = require('path');
// Implementing the UI
export async function UserInterface(event, context, callback) {
// Capture data event
const e = event.queryStringParameters;
// Get UI parameters
let params = await ui(e);
var htmlContent = fs.readFileSync(path.resolve(process.cwd(), './views/' + 'ui.ejs'), 'utf8');
var template = ejs.compile(htmlContent);
return {
statusCode: 200,
headers: { 'Content-type': 'text/html' },
body: JSON.stringify(template(params)),
};
};
The Fix:
Replacing 'body:JSON.stringify(template(params))' with 'body:template(params)' got rid of the '\r\n\r\n\n\r'.
But the css files and images are still not working in the web page.
How do I configure the CSS and the images directories to load into the web page?
handler.js
import {ui} from './index.js';
var ejs = require('ejs');
var fs = require('fs');
const path = require('path');
// Implementing the UI
export async function UserInterface(event, context, callback) {
// Capture data event
const e = event.queryStringParameters;
// Get UI parameters
let params = await ui(e);
var htmlContent = fs.readFileSync(path.resolve(process.cwd(), './views/' + 'ui.ejs'), 'utf8');
var template = ejs.compile(htmlContent);
return {
statusCode: 200,
headers: { 'Content-type': 'text/html' },
body: template(params),
};
};
The ui.js looks something like this:
ui.js
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="/public/assets/css/bootstrap.min.css"><!-- Link to bootstrap library-->
<link rel="stylesheet" href="/public/assets/css/materialize.min.css"><!-- Link to materialize library-->
<link rel="shortcut icon" type="image/svg" href="/public/assets/img/site/logo.svg"/><!-- Link to title icon logo-->
<title><%= title %></title>
</head>
<body>
And the index view engine like this:
index.js
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine

Exporting object in Webpack 5

I'm building a JS library with Webpack and trying to export an object.
import jwt_decode from "jwt-decode";
console.log(location.hash.replace('#', ''));
export var upstream = {
user: {
getUserDetails: () => {
if (location.hash) {
return jwt_decode(location.hash.replace('#', ''));
} else {
return null;
}
}
}
}
In my client-side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UpStream</title>
</head>
<body>
<script src="http://localhost:8080/app.js"> <!--server is up, connects fine-->
</script>
<script>
console.log(upstream);
</script>
</body>
</html>
The console.log(); statement works as intended, but I cannot access the upstream object. Any pointers?
To be able to access upstream via window or just upstream you would need to ensure you specify the export as a Library with libraryTarget of 'window'.
Hopefully that helps!

Categories

Resources