How to navigate between two html files in a Expressjs project - html

am relatively new to expressjs and for the life of me i can not figure out how to navigate between two HTML files in the root folder. Am using bootstrap anjularjs and expressjs for my project.
I have currently used the following code in the routes directory:
var express = require('express');
var router = express.Router();
var app = express();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('profile', { title: 'Express' });
});
router.get('/profile', function(req, res, next){
res.render('profile', {title: ''});
});
module.exports = router;
In addition to this i have also made use of this statement in the app.js file to try and help with navigation:
app.use('/static',express.static(path.join(__dirname, 'views')))
app.use('/html', express.static("html"));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/profile', function (req,res){
res.render('profile', {
title: 'Profile'
});
});
So my problem is this current error, any assistance with this would be appreciated:
Error: Failed to lookup view "error" in views directory "C:\Users\Brian Manda\Documents\fmg_code\views"
at EventEmitter.render (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\application.js:579:17)
at ServerResponse.render (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\response.js:960:7)
at C:\Users\Brian Manda\Documents\fmg_code\app.js:52:7
at Layer.handle_error (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:310:13)
at C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:271:10)
at C:\Users\Brian Manda\Documents\fmg_code\app.js:41:2
at Layer.handle [as handle_request] (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\layer.js:95:5)

Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.
If you dont set the "ejs", automatically the app get the .html file, because res.render is for that.
In the case, my html file have name: index inside public folder.
If your index is .html:
var app = express();
app.get('/', function(req, res){
res.render("../public/index"); //the archive html file
});
If you index is '.ejs':
var app = express();
app.set('view engine', 'ejs'); // set the index.ejs file
app.get('/', function(req, res){
res.render("../public/index.ejs"); // if you want, remove the .ejs, is optional,
});
Reference here.

Related

Showing HTML file in Node js Application

I am new on Node.js and I have app.js file like:
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?
I tried
app.get('/',function(req,res) {
res.sendFile('index.html');
});
But didn't see a difference.
To make your code example work you'll need to specify an absolute path, try using this:
res.sendFile(__dirname + "/index.html");
Another way would be to use EJS (https://ejs.co/)
In your example, you could do the following:
Install EJS:
npm install ejs
Set the View Engine to EJS:
app.set('view engine', 'ejs')
- Move your index.html file to a folder called "views" and also rename the file to index.ejs
views/index.ejs
In your app.get() handler, use:
res.render('index')
Final Result:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
const port = 8080;
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`App running on http://localhost:${port}`);
});
(note: I also moved your console.log to inside app.listen)
I found this on another stack overflow question, it should work
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});

How to render html code stored as string?

Hi I am trying to send the contents of string stored in mongo db through res.render. However, if I check after sending this string, the tag appears in the form of a string and does not appear in html, so I want to know how to solve it.
router.get("/:id", async function (req, res) {
var article = await Article.findById(req.params.id);
console.log(article);
res.setHeader("Content-type", "text/html");
res.render("articles/article", { article: article });
});
article = "<p>내용입니다.</p>"
here is the working example. You have to install the pug template engine or any other template engine. See the test. pug file and note that if the variable is HTML content then we have to use the syntax "!{para}" or if the variable is a simple string then we can use the syntax "#{para}".
so the folder structure would be like
app.js
views ->test.pug
// app.js file
var express = require('express');
var app = express();
var PORT = 3000;
app.set('view engine', 'pug');
app.use('/', function(req, res, next){
res.render('test', {para : `<p>This is paragraph</p>`});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
// html file test.pug
<div>!{para}</div>

Adding another page other than index.html

I started my own VPS, and started a web server using NGINX. I have an index.html. How do I create other pages, like an about page, and having it live at www.my-domain-name.com/about/
Does this mean I have to edit my app.js file, if so, how?
Amendment: I added Lazar's suggested amendment to the Express code to get the about.html.
'use strict';
const express = require("express");
const app = express();
// Static css/js files
app.use('/static', express.static('./dist'));
app.get("/", function(req, res) {
res.sendFile( __dirname + '/index.html');
});
app.get("/about", function(req, res) {
res.sendFile( __dirname + '/about.html');
});
const port = 3001;
// Start server
app.listen(port, function() {
console.log("Listening on " + port);
});
In index.html, the link to the about page is:
About me.
Both /about and /about.html don't currently work and receive the error message: Cannot GET /about.html
Edit: I am using forever, so I had to forever restartall
Considering that you are using express, for every created route, create appropriate html page - or use some other thing, like handlebars, etc.
For example you created index.html for "/" route.
For about us route, create aboutus.html
app.get("/aboutus", function(req, res) {
res.sendFile( __dirname + '/aboutus.html');
});
and so on...
For more info check their official web page: https://expressjs.com/

Is there a way to include jade file directly in html file?

How can I combine a node.js website that its frontend is based on html with another node.js website that its frontend is based on jade template engine? I am using Express framework.
On the frontend there are four files: index.html, index2.html, chat1.html, chat2.html, which are located in the public folder. The blog website that I want to add to this website has only jade template engine, which are located in the views folder.
The index.html (which is in public folder) is the entry point to the home page of the website. When from index.html I refer to index3.jade, which is the Home page of the second app, i.e., blog jade app, Chrome browser states: "404 Not Found". However, I can go to the other two pages of the blog jade website, i.e., Add Post and Add Category. It is only the Home page of the blog jade app that is not being displayed.
So, I am not able to see only the Home page of the blog jade app, which starts at the root directory. Both the html app and the blog jade app start at the root directory. I was able to make the blog jade app to be displayed at the root directory, but then I could not see the html app, which also starts at the root directory.
Here is how I referred to each file from index.html front page:
`<li>gallery</li>`
`<li>chat</li>`
`<li>blog</li>`
Is there a way to have the home page of the blog jade app to be displayed at a directory other than the root directory?
Here is the related app.js code:
// Gallery HTML Code
var routes = require('./');
app.get('/public/index.html');
// Blog Code
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var routes = require('./');
var routes = require('./routes/index3');
var posts = require('./routes/posts');
var categories = require('./routes/categories');
var app = express();
app.locals.moment = require('moment');
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect-Flash from Express-Messages
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/index3', routes);
app.use('/posts', posts);
app.use('/categories', categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is the related code from index3.js in the routes folder:
router.get('index3', function(req, res, next) {
var db = req.db;
var posts = db.get('posts');
posts.find({}, {}, function(err, posts) {
res.render('index3', { posts: posts });
});
});
module.exports = router;
Here is the related code from index.js in the routes folder:
router.get('/', function(req, res, next) {
res.render('public/index.html');
});
module.exports = router;

Output JSON object in node js using express

This is my first time using Node and I am using the express framework. I am trying to output a json object when on the "calendar" page (seen in main.js). When I run the router (main.js) I get this error: Error: ENOENT, no such file or directory '/Users/Macbook/Desktop/node/views/('calendar.ejs')'
Basically I want to output my JSON object defined in main.js into my html file. Can someone please explain to me why the server cannot find the calendar file. It can find index.ejs but not calendar. And is this the right way to do what I want to achieve?
Below is the directory structure I have setup:
-------node_modules
-------routes
-------------main.js
-------views
------------calendar.ejs
------------index.ejs
-------package.json
-------server.js
This is my server.js code:
var express=require('express');
var app=express();
require('./routes/main')(app);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
var server=app.listen(3000,function(){
console.log("We have started our server on port 3000");
});
This is my main.js code:
module.exports=function(app){
app.get('/', function(req,res){
res.render('index',{title:"Home page"});
});
app.get('/calendar',function(req,res){
res.json({"foo": "bar"});
});
}
Just a guess.
First you set the GET /calendar route with require('./routes/main')(app);.
Then you overwrite the GET /calendar route with app.set('views',__dirname + '/views');.
You need to choose whether the GET /calendar returns rendered HTML or the JSON data.
Few things to note :
Since your view files are of .ejs extensions so you can comment below line.(documentation)
app.engine('html', require('ejs').renderFile);
It is convention to pass the `app' reference to routers after you have set all the configurations, middleware order matters when working on ExpressJS.
server.js
var express=require('express');
var app=express();
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'ejs');
require('./routes/main')(app);
var server=app.listen(3000,function(){
console.log("We have started our server on port 3000");
});
main.js
module.exports=function(app){
app.get('/', function(req,res){
res.render('index',{title:"Home page"});
});
app.get('/calendar',function(req,res){
res.render('calendar',{"foo": "bar"});
});
}