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

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'));

Related

Using Firebase with Express: app.post() not working with existing files under the public folder

I am currently learning express.js and building a dynamic website with firebase. The website is really simple, it takes two numbers from user input and sends back the sum. I have one test.html in the public folder, which contains the html form, inputs, and submit button. In index.js in the functions folder I specified the app.post method, and in firebase.json in my project folder the rewrite properties is the same as the tutorial from firebase: Use a web framework.
/public/test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Calculator</h1>
<form action="/test" method="post">
<input type="text" name="num1" placeholder="Enter your first number">
<input type="text" name="num2" placeholder="Enter your second number">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
/functions/index.js:
const functions = require("firebase-functions");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/test", (req, res) => {
res.send("The answer is " + (Number(req.body.num1) + Number(req.body.num2)));
});
exports.app = functions.https.onRequest(app);
/firebase.json:
{
"hosting": {
"public": "public",
......
"rewrites": [ {
"source": "**",
"function": "app"
} ]
}
......
}
When I open the page, the form, boxes, and submit button appear just as specified in the test.html file. I expect that when I enter two numbers in the input boxes the website would return their sum, as specified in index.js. However, when I click the submit button, nothing happens.

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.

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

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

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.

Why isn't my public folder fetching files for '/' URL in my NodeJS App?

I am trying to place static files in my public folder such as the html,css and js files but they won't fetch to the get url ('/').
Here is my folder structure
app.js
node_modules
--express
package.json
public
--style.css
My app is:
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use('/assets', express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send('<html><head><link href=assets/style.css type=text/css rel=stylesheet/></head><body><h1>Hello World</h1></body></html>');
});
app.get('/person/:id', function(req, res){
res.send('<html><head></head><body><h1>Person: ' + req.params.id + '</h1></body></html>');
});
app.get('/api', function(req, res){
res.json({ firstname: 'John', lastname: 'Doe' });
});
app.listen(port);
Style code is:
style.css:
body {
font-family: Arial, Helvetica, sans-sarif;
}
Your problem is, because
<link href=assets/style.css type=text/css rel=stylesheet/>
is equal to
<link href=assets/style.css type=text/css rel="stylesheet/">
If you don't use quotes then the value is terminated by one of the following characters: ", ', =, >, <, or ` (See W3C: 4.4. Attributes for more details). As of that your value is terminated by the > value is stylesheet/.
Because of that the rel of your link is stylesheet/ instead of stylesheet and thats why no stylesheet is loaded.
So either you have to add a space between stylesheet and /:
<link href=assets/style.css type=text/css rel=stylesheet />
or you need to use quotes.
Can you rename "public" to "assets", then use...
app.use(express.static('assets'));
There is syntax error in your HTML statement that links to the CSS file. You forgot to enclose the values in double quotes.
Please use the following format:
<link rel="stylesheet" type="text/css" href="assets/style.css">
If you are using ES6 supporting Node.JS then you can use the back-ticks(``) to better format the inline HTML code like:
app.get('/', function(req, res){
res.send(`
<html>
<head>
<link rel="stylesheet" type="text/css" href="assets/style.css">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>`
);
});

Categories

Resources