NodeJS ejs Failed to lookup view "layout" in views directory - node.js

I want to implement my outsourced .ejs files into the layouts/admin.ejs direction. But it throws this error. I want my outsourced header, footer and navbar to be shown. All these files are stored in /views/partials/admin/filename.ejs
My layout is in /views/layouts/admin.ejs
<%- head -%>
<body>
<!-- Navigation Top -->
<%- navigation -%>
<!-- Page Content -->
<div class="container-fluid main">
<%- footer -%>
</div>
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
so this is my app.js
const
express = require('express'),
path = require('path'),
crypto = require('crypto'),
mongoose = require('mongoose'),
multer = require('multer'),
GridFsStorage = require('multer-gridfs-storage'),
Grid = require('gridfs-stream'),
methodOverride = require('method-override'),
bodyParser = require('body-parser');
const app = express();
const port = 3003;
// Middleware
app.use(bodyParser.json());
app.use(methodOverride('_method')); // Use query string in form
// Set view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// #route get /admin
// #desc route to admin panel
const partialRoute = '/views/partials/';
app.get('/', (req, res) => {
res.render('layouts/admin', {
head: res.sendFile(__dirname + partials + 'head.ejs');
footer: res.sendFile(__dirname + partials + 'footer.ejs');
navigation: res.sendFile(__dirname + partials + 'navigaiton.ejs');
});
app.listen(port, () => {
console.log(`Server running at port ${port}`);
})
I tried to change the foldernames and routes and also removed all <% ejs but nothing works

hmmm... im using pug and not ejs, but it seems, that the directoryname is wrong/undefined?
You initialize partialRoute, but not partials?
Maybe im blind
const partialRoute = '/views/partials/';
app.get('/', (req, res) => {
res.render('layouts/admin', {
head: res.sendFile(__dirname + partials + 'head.ejs');
footer: res.sendFile(__dirname + partials + 'footer.ejs');
navigation: res.sendFile(__dirname + partials + 'navigaiton.ejs');
});

Related

How to solve net::ERR_ABORTED 404 in Nodejs

I am currently towards the end of my project but there is one error I am receiving still. I cannot seem to figure out why I am receiving the error:
"Failed to load resource: the server responded with a status of 404
(Not Found)".
Below is my file layout, server.js and the script tag. I have my layout the same as all the other projects I have made in the past but for some reason this error keeps popping.
server.js
"use strict";
// DEPENDENCIES
require("dotenv").config();
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const path = require("path");
const ejs = require("ejs");
const logger = require("morgan");
var createError = require("http-errors");
var cookieParser = require("cookie-parser");
const flash = require("connect-flash");
const favicon = require("serve-favicon");
// ROUTES REQUIRED
const main = require("./routes/main");
const about = require("./routes/about");
const contact = require("./routes/contact");
const profile = require("./routes/profile");
const pricing = require("./routes/pricing");
const help = require("./routes/help");
const login = require("./routes/login");
const signup = require("./routes/signup");
const forgot_password = require("./routes/forgot-password");
// PORT
const port = 3000;
const app = express();
// COOKIES AND SESSION
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
// DATABASE
require("./config/database.js");
// PASSPORT AUTHENTICATION
require("./config/passport.js");
// VIEWS SETUP
app.set("views", path.join(__dirname + "/views"));
app.set("view engine", "ejs");
app.set("view cache", false);
// MIDDLEWARE
app.use(favicon(__dirname + "/public/favicon.ico"));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use("/public", express.static(path.join(__dirname + "/public")));
app.use(flash());
// ROUTES
app.use("/", main);
app.use("/about", about);
app.use("/contact", contact);
// PRICING
app.use("/pricing", pricing);
// PROFILE
app.use("/profile", profile);
app.use("/help", help);
app.use("/login", login);
app.use("/signup", signup);
app.use("/forgot-password", forgot_password);
// Logout
app.get("/logout", function (req, res) {
res.clearCookie("connect.sid");
res.redirect("/");
});
app.listen(process.env.PORT || port, (err, done) => {
if (!err) {
console.log({ message: "success!" });
} else {
return err;
}
});
home.ejs(home page layout with scripts.)
--------------------------------------------------------------------------
<section class="ad-analytics">
<div class="container-fluid ad-analytics__contain">
<div class="row ad-analytics__row">
<div class="col-md-6" id="meetings-img-holder">
<!-- bg-img holder -->
</div>
<div class="col-md-6 ad-analytics__textbox">
<div class="col-sm-12 ad-analytics__info">
<h1 class="h2">Analytical Precision</h1>
<p>
Getting ahead of the curve is the best way to scale above the
compeititon. With our machine learning tools, you can leverage
your data and get real insight on what your customers want from
you.
</p>
<a
class="btn btn-outline-light btn-sm"
href="/machine-learning"
role="button"
>Get Started</a
>
</div>
</div>
</div>
</div>
</section>
<%- include('partials/footer.ejs') %>
<%- include('partials/scripts.ejs') %>
</body>
</html>
------------------------------------------------------------------------------------
(Inside partials/script.js)
<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>
<script type="javascript" src="/server.js"></script>
File Layout
You shouldn't use <script> tags to import server side files, like for an example server.js, this file is used to run the node server
let's say you make a script for home page, you need to save it inside /public and the send it to client to be interpreted by the browser by adding it to partials/scripts.ejs
example
<script type="javascript" src="/home_script.js"></script>
the path would be
public/home_script.js
Edit:
it feels like you're still a bit confused so i'll take a example
in server.js you have
const main = require("./routes/main");
app.use("/", main);
think about the file main.js like taking a function from server.js and moving it to a single file
now in main.js i'm guessing you have a function like this:
router.get('/', (req,res,next) => {
res.render('home.ejs')
})
the code above is part of server side code and shouldn't be sent to the user(the client)
now inside home.ejs
you have your partials and then a section for scripts
<script type="javascript" src="/bootstrap.bundle.min.js"></script>
<script type="javascript" src="/home_script.js"></script>
this file home_script should contains stuff that you want to do once the page arrives the user (we call this client side)
as an example:
if you have button and you want to do something when you click you write that part of javascript inside home_script.js

When rendering ejs file, it does not show properly

I am trying to render ejs file from nodejs express.
But it shows html codes with thes character � everywhere.
let express = require('express');
let app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'The index page!' })
});
And index.ejs is
<html>
<head>
<title><%= title %></title>
</head>
<body>
welcome <%= title %>;
</body>
</html>
What did do I do wrong?
The server needs to be started
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'The index page!' })
});
app.listen(3000);

ReactJS + Express.js + React-Bootstrap: onClick handler for Bootstrap button not working

I just started learning ReactJS and I can't seem to get the onClick handler to work.
I followed the Express.js application generator tutorial and ended up with the following code.
Can somebody please tell me what's wrong?
//app.js file
var express = require('express');
var path = require('path');
// routes
var launch = require('./routes/launch');
var app = express();
// view engine setup
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// attach url to routes
app.use('/', launch);
//launch.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('launch', {});
});
module.exports = router;
//launch.jsx code
var React = require('react');
var DefaultLayout = require('./layouts/default');
// bootstrap
import {Button, Grid, Row, Col, Clearfix, Image, FormGroup, InputGroup, FormControl} from 'react-bootstrap';
var LaunchView = React.createClass({
render: function() {
return (
<FormGroup>
<InputGroup>
<FormControl id="launch-email" type="email" placeholder="Email" />
<InputGroup.Button>
<Button id="launch-submit" className="button-green" onClick={this.handleSubmit}>Submit</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
);
},
handleSubmit: function(){
alert("woot");
}
});
module.exports = LaunchView;
doesn't support attaching events on the client-side or doing client-side updates afterwards.
https://github.com/reactjs/express-react-views/issues/2
You can implemented a small "hack" and insert a script file which explicitly sets element's onclick behavior. Keep in mind that DOM has to be loaded in order to attach events.
let myElement = document.getElementsByClassName("overlay")[0];
myElement.addEventListener('click', () => {myElement.style.display = 'none';});
It's not elegant, but it works.

Angular '/' route not working with Express

I'm trying to serve a home view using Express/Angular, such that when the root url ('/') is accessed, a view is loaded. Right now navigating to http://localhost:3000 displays an empty page with <!-- ngView: --> and nothing else. Navigating to http://localhost:3000/about displays the about page as expected. How do I get the home partial to display when the root is accessed?
app.js (w/ Express 4.9.0)
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var routes = require('./routes');
var path = path = require('path');
app.set('port', process.env.PORT || 3000);
app.use(express.static(path.join(__dirname, 'public')));
server.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
app.get('*', routes.index);
routes/routes.js
exports.index = function(req, res){
res.render('index');
};
exports.partials = function (req, res) {
var name = req.params.name;
res.render('partials/' + name);
};
views/index.jade
doctype
html(ng-app="myApp")
head
meta(charset='utf8')
base(href='/')
title Angular Express Seed App
link(rel='stylesheet', href='/css/app.css')
body
div(ng-controller='AppCtrl')
div(ng-view)
script(src='bower_components/angular-loader/angular-loader.js')
script(src='bower_components/angular/angular.js')
script(src='bower_components/angular-route/angular-route.js')
script(src='bower_components/socket.io-client/socket.io.js')
script(src='js/app.js')
script(src='js/main.js')
script(src='js/services.js')
script(src='js/controllers.js')
script(src='js/filters.js')
script(src='js/directives.js')
public/js/app.js
angular.module('myApp', [
'myApp.controllers',
'myApp.filters',
'myApp.services',
'myApp.directives',
'ngRoute'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateURL: 'partials/home',
controller: 'MyCtrl2'
}).
when('/about', {
templateUrl: 'partials/about',
controller: 'MyCtrl1'
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
});
I also have a views/partials/home.jade and a views/partials/about.jade
I think you may have misspelled templateUrl in
when('/', {
templateURL: 'partials/home',
controller: 'MyCtrl2'
}).

loading jade template through angular

I am working on a single page web app, and I wanted to load in jade views with my angular template but I am struggling to wrap my head exactly how to do so.
Here is my angular template:
index.html
<!doctype html>
<html ng-app="test">
<head>
<title>My Angular App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script type="text/javascript" src="/javascripts/app2.js"></script>
</head>
<body>
<p> Hello </p>
<div>
<div ng-view></div>
</div>
</body>
</html>
I made a controller for my angular template: navigation.js
angular.module('test', [])
.config(viewRouter);
function viewRouter ($routeProvider){
$routeProvider
.when('/', {templateURL: 'views/index.jade'});
}
Here I am trying to use a jade template to render onto the page, but it does not seem to be working.
I have a view jade templates,
index.jade
extends layout
block content
h1= title
include partials/menu
.views-wrapper
include partials/login
layout.jade:
doctype
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(src='//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
script(src='/javascripts/navigation.js')
menu.jade:
ul
li.a VIEW A
li.b VIEW B
li.c VIEW C
li.l VIEW LOGIN2
I also have a view simple templates (named a.jade, b.jade, and c.jade) which just have simple headers displaying a name as a test to see if the routing works. I am struggling to get these templates to connect, I can't seem to wrap my head around, nor find an answer as to how I can display my jade views through my angular template. Before I was not using an angular template, but decided to use one in order to deal with URL more easily.
this is my app.js on my server side:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser('cookies monster')); // Cookie secret
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.set('public', path.join(__dirname, 'public'));
/*
* Views
*/
//app.get('/', routes.index);
app.get('/', function(req, res, next){
return res.sendfile(app.get('public') + '/index.html');
});
app.get('/users', user.list);
app.get('/a', routes.a);
app.get('/b', routes.b);
app.get('/c', routes.c);
app.get('/login2', routes.login2);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and this is a routes controller that I had to render the views before I decided to use angular
index.js:
exports.index = function(req, res){
res.render('index', { title: 'New Test' });
};
// View A
exports.a = function(req, res) {
res.render('partials/a', { layout: false, test: 'a' });
};
// View B
exports.b = function(req, res) {
res.render('partials/b', { layout: false, test: 'b' });
};
exports.c = function(req, res) {
res.render('partials/c', { layout: false, test: 'c' });
};
exports.login2 = function(req, res) {
res.render('partials/login2', { layout: false, test: 'login2' });
};
I know this is a lot of code to look at, but I would really appreciate any help.
Check my answer on stackoverflow about using AngularJS seed for working with Jade, it can help you with your question.

Resources