I am using the express ejs layouts but only the mainPage can read the css the other pages don't read it (the css, the html read it).
Another question, if I wanted to use another layout (ex: layout2.ejs) what would i do to act on a specific page.
Tree:
Project
- public
- js
- css
- style.css
- routes
- index.js
- users.js
- views
- layout.ejs
- mainPage.ejs
- login.ejs
...
- app.js
I am using particles.js if you need to know.
app.js
const express = require('express');
const expL = require('express-ejs-layouts');
const app = express(); //Create a Web Application
//EJS
app.use(expL);
app.set('view engine', 'ejs')
//Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
app.listen(3000, ()=> console.log('Listening at 3000'));
app.use(express.static('public'))
index.js
const express = require('express');
const router = express.Router();
router.get('/',(req, res) => {
res.render('mainPage',{title: 'Groupy'}); (THIS ONE WORK AND READ THE CSS)
});
module.exports = router;
users.js
const express = require('express');
const router = express.Router();
//Login Page
router.get('/login',function(req, res) {
res.render('login',{title: 'Groupy Login'}); (DON'T READ CSS)
});
//Register Page
router.get('/register',function(req, res) {
res.render('register',{title: 'Groupy Register'}); (DON'T READ CSS)
});
module.exports = router;
layout.ejs
<html>
<head>
<script type="text/javascript" src="code.js"></script>
<link rel="stylesheet" type="text/css" href="./css/style.css">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</script>
<title><%= title %></title>
</head>
<body>
<div id="particles-js"> </div>
<script src="js/particles.min.js"></script>
<script src="js/app.js"></script>
<h2>teste</h2>
<%- body %>
</body>
mainPage.ejs
<h1 id="title">Groupy</h1>
<div id="firstBox">
<div id="SignIn">Register <div id="login">Login</div>
</div>
</div>
<br>
<div id="mainBox"></div>
login.ejs
<h1 id="title">Groupy Login</h1>
Reseult of login (without CSS):
teste
Groupy Login
Can you try the following app.use instead of app.use(express.static('public'))
app.use('/public', express.static(path.join(__dirname, 'public')));
Also you should import path module
const path = require('path');
The error was the path of css and javascript (particles.js)
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="/js/particles.min.js"></script>
<script src="/js/app.js"></script>
Related
In my project I use the following handlebars template (under views/layouts/main.handlebars) :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
{{{css}}}
{{{js}}}
</head>
<body>
<header>
<!-- some content here -->
</header>
<main>
{{{body}}}
</main>
<footer>
I am footer
</footer>
</body>
</html>
And for my home page I made a simple content named ./views/home.handlebars
<h1>Hello</h1>
In order to render the template I use express handlebars:
const express = require('express');
const path = require('path');
const express_handlebars = require('express-handlebars');
const app = express();
const hbs = express_handlebars.create({
// Specify helpers which are only registered on this instance.
defaultLayout: 'main'
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views',path.join(__dirname,'/../../views'));
app.get('/', (req, res, next) => {
res.render('home');
});
app.listen(3000);
What I want is to place some javascript once I visit http://0.0.0.0:3000 for example:
<script>alert("Hello");</script>
Where I want to be appended is in {{{js}}} partial. Is there a way to do it?
An approach of mine is to make the js section as an array and place a base html5 tag, specifying where each page will find its js:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
{{{css}}}
{{#each js}}
<script src="{{this}}"></script>
{{/each}}
</head>
<body>
<header>
<!-- some content here -->
</header>
<main>
{{{body}}}
</main>
<footer>
I am footer
</footer>
</body>
</html>
For my application's js I use separate files per page and I do not embed it inside my homepage into a folder named static:
const express = require('express');
const path = require('path');
const express_handlebars = require('express-handlebars');
const app = express();
const hbs = express_handlebars.create({
// Specify helpers which are only registered on this instance.
defaultLayout: 'main'
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views',path.join(__dirname,'/../../views'));
app.use('/static',express.static(path.join(__dirname,'/../static')));
app.get('/', (req, res, next) => {
res.render('home',{
title:'Homepage',
js: [
'/static/js/home.js'
],
baseUrl: `${req.protocol}://${req.get('host')}`
});
});
app.listen(3000);
Then upon static folder I place the necessary js files that will run upon the browser. I found it as an easy-peasy solution and keep client-side js into its own folder.
I have an electron app where i use preact package to create components and serve them in an index.html and i want to turn it to a web app
my file structure is
-- src/
---- workers/
---- components/
---- index.js (rendering the div#root)
-- index.html (with div#root and script src='src/index.js')
the js files contain nodejs code
i tried to create a root file index.js with a server pointing to index.html but the js inside src/ doesn't work
index.html :
<!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>title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="root"></div>
<script src="./src/index.js"></script>
</body>
</html>
src/index.js:
const { render, h } = require("preact");
const App = require("./components/App");
const rootEl = document.getElementById("root");
render(h(App, { rootEl }), rootEl);
i tried this:
const path = require("path");
const express = require("express");
const app = express();
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.listen(process.env.PORT || 4433, () => {});
I keep getting the following MIME error while trying to lead in a stylesheet to my application:
I have followed the newest issues on this MIME error for hours now with no luck. I have told my Express development server to pull resource from a static file and still no luck. Here is my development hierarchy:
I will include my code below. Any help is appreciated.
**index.html**
<!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">
<meta name="description" content="">
<meta name="subject" content="">
<meta name="author" content="">
<link rel="stylesheet" href="/public/styles/customStyles.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Clone Application</title>
</head>
<body>
<div class="conatiner-fluid">
<nav class="nav-wrapper">
Hello Again
</nav>
Hello World
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</body>
</html>
**Server.js**
const express = require('express');
const app = express();
const router = require("./router");
const path = require("path");
const PORT = 3000;
app.use(router, express.static('public'));
app.listen(PORT, () => {
console.log("Listening on port: " + PORT);
});
**router.js**
const express = require('express');
const router = express.Router();
const pages = "/public/pages/";
router.get('/home', (req, res) => {
res.sendFile(__dirname + "/public/pages/home/index.html")
})
module.exports = router;
Your HTML links to the stylesheet at /public/styles/customStyles.css
However, the correct URI is /styles/customStyles.css (or preferably without the first slash, styles/customStyles.css so it will continue to work if the page isn't in the root).
app.use(router, express.static('public')); tells express to serve static files under the 'public' folder, so adding 'public' to your CSS URI is incorrect.
You're getting an HTML MIME type due to the Express default error page ('Cannot GET..')
My folder structure is something like this:
app
controller
routes
app.js
Within my controller folder, I have
controller
sites folder
index.html
style.css
controller.js
Here is my Controller.js
const express = require('express');
app = express();
app.use(express.static('../site'));
module.exports= {
index : (req, res, next)=>{
res.status(200);
res.sendFile(__dirname + '\\site\\index.html');
}
};
And here is my index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Template</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
When I run the server and do a GET request, Express gives a 404 on the CSS file. Where am I going wrong?
I am setting up the environment for a node js app. But the views/ejs files are not being rendered.
If i do:
app.get("/", function(req, res){
res.send('Hello');
});
it works.
But if i do:
app.get("/", function(req, res){
res.render("welcome");
});
it doesn't.
my app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const indexRoutes = require("./routes/index");
const userRoutes = require("./routes/user");
const ejsLayouts = require("express-ejs-layouts");
const path = require("path");
mongoose.connect("mongodb://localhost/userAuth", function(err, res) {
if (err) throw err;
console.log("Connected to database");
});
//EJS
app.set('view engine','ejs');
app.use(ejsLayouts);
app.use(express.static(__dirname + '/public'));
app.set('views',path.join(__dirname+'/views'))
//ROUTES
app.use("/", indexRoutes);
app.use("/user", userRoutes);
app.listen(3000, function() {
console.log("server started");
});
my index.js file (userLogin/routes/index.js)
const express=require("express");
path = require('path');
router= express.Router();
router.get("/",function(req,res){
res.render("welcome");
});
module.exports = router;
my folder structure
userLogin
/..
/routes
/index.js
/views
/welcome.ejs
I have an h1 element olny in welcome.ejs file.
Looking at the code you provided, in index.js you are trying to render a view called check, when the only view you have is called welcome. Your paths and routes look to be correct, rendering the correct view should work.
app.engine('html', require('ejs').renderFile);
if u woudlike to render .html files
then
fs.readFile(path.resolve(__dirname + '/../public/views/logs.html'), 'utf-8', (err, content) => {
let renderedHtml = ejs.render(content, {'user': req.session.db}); //get redered HTML code
res.end(renderedHtml);
})
you should have views/layouts/layout.ejs file if you are using express-ejs-layouts npm
inside app.js :
const ejs =require('ejs');
const ejsLayouts = require("express-ejs-layouts");
app.set('view engine','ejs');
app.use(ejsLayouts);
app.set('layout', 'layouts/layout');
layout.ejs file has common layout that follow all files
if you are using bootstrap then your layout.ejs file would be like :
<!doctype html>
<html lang="en">
<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.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<?- body ?>
</body>
</html>
so now other ejs pages will only have content to display
like welcome.ejs file is
<h1>Welcome Page</h1>