Output JSON object in node js using express - json

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"});
});
}

Related

Cannot access static files from URL in express application

I have built a basic express app as below -
index.js
const express = require("express");
const app = express();
app.use(express.static(__dirname + "public"));
app.get("/", (req, res) => {
res.json({ message: "Hello World!" });
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
I want to serve static files directly from the browser URL, and according to this express doc page it is indeed possible.
Accordingly, I have created a folder called public in the root folder and have kept two files in it - one demo.html, and one image.jpg. My folder structure -
express-app
|- index.js
|- public
|- image.jpg
|- demo.html
However, when I try to access http://localhost:3000/demo.html or http://localhost:3000/image.jpg, I get a Cannot GET error.
Can anybody please tell me why it isn't working?
app.use(express.static(__dirname + "public"));
__dirname does not include a trailing slash.
__dirname + "public" will give you something like: /home/me/express-apppublic — a directory that doesn't exist.
The documentation you link to shows the use of path.join to include the correct directory separator for your operating system.
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
Don't omit that part!

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

I want to load route first , after that i want to load the static files from public folder in node.js?

i want to load the route '/' first while running the app.js file of node.js,
as it is performing authentication and redirects to file index.html
As, the program is not able to find the index.html it gives me error.
So, i want to load the public folder after the authentication is done in app.js
app.use('/', passport.authenticate(WebAppStrategy.STRATEGY_NAME), function(req, res){
});
after then it should be redirected to index.html resided in public folder
app.use(express.static(path.join(__dirname, 'public')));
// Set 'views' directory for any views
// being rendered res.render()
app.set('views', path.join(__dirname, 'views'));
you can use next()
app.use(passport.authenticate(WebAppStrategy.STRATEGY_NAME), function(req, res, next) {
// do your authentication
next();
});
app.use(express.static(path.join(__dirname, "public")));
// Set 'views' directory for any views
// being rendered res.render()
app.set("views", path.join(__dirname, "views"));

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/

How to navigate between two html files in a Expressjs project

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.