Why there is a need to create a server in NodeJS application? - node.js

Learning Nodejs for my personal projects. Analysing other developers code examples, watching youtube videos. I noticed one thing that I don't understand completely, why most of nodejs examples I come across have a code part for http server initiation and port listening? But application itself not using any http related things like processing http requests/responses. For example:
const express = require('express')
const path = require('path')
const http = require('http')
const cors = require('cors')
const PORT = process.env.PORT || 5000
const app = express();
const server = http.createServer(app).listen(PORT, () => console.log(`Listening on ${PORT}\n`))
app.use(express.static(path.join(__dirname, 'public')))
app.use(cors({ credentials: true, origin: '*' }))
If my nodejs application is a script that needs to be run on server side that collects some information from other API's and stores in a database, etc., do I need to create and start HTTP server anyway?

why most of nodejs examples I come across have a code part for http server initiation and port listening?
Because that's how people use nodejs most of the time: as a web server. Which doesn't mean it is mandatory or even a good practice.
do I need to create and start HTTP server anyway?
Of course not. Why would you do that if you don't need it? Do not worry about tutorials or examples, these don't know about your case and your needs.

Related

How to manage NodeJs app code to reduce clutter

Hie,
I am developing a Nodejs (Express) web app and pretty much new to this technology. So far I see that there can only be one point of entry mine being my the server.js file. Now it seems all requests and/or processes should be initiated here which is fine for a smaller application, but my site has about 25 page routes already all of who's request should be handle here. I also have a dozen or so Ajax requests are handled here. Now even though I am processing different functions e.g CRUD operations in separate files, I still fear at some point my code will become unreadable as the server.js file get longer
const express = require("express")
const path = require("path")
const exphbs = require("express-handlebars")
let app = express()
app.set("views",path.join(__dirname,'templates'))
app.engine('handlebars',exphbs({defaultLayout:'main'}))
app.set('view engine','handlebars')
app.set('port',(process.env.PORT || 3000));
app.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/home',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/register',(req,res)=>{
res.render('register',{'title':'Register'});
});
app.use(express.static(path.join(__dirname, '/public')));
app.listen(app.get('port'),()=>{
console.log(`Server started on port : ${app.get('port')}`)
})
So far my server.js is this small, but it just hit me that I have 25 pages and multiple Ajax processes on each.
Yes, you have to structure your routes. For that, you have to look at Express Router. You have to create different route files based on a specific resource.
/routes/homeRoutes.js
const express = require("express");
const router = express.Router();
router.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
module.exports = router;
server.js
const homeRoutes = require("./routes/homeRoutes");
app.use("/api/v1/home", homeRoutes);
Also, have a look at the following links for a better understanding of project structure and express router.
https://expressjs.com/en/guide/routing.html
project structure
I think what you are looking for is splitting the code up in local modules. You can place parts of your code in separate files, include module.exports at the end and then require(./filename.js) them in your server.js.
You can see an example here: https://www.tutorialsteacher.com/nodejs/nodejs-local-modules

http2 in node.js, express, socket.io client

I am building a web app that uses a express and node.js in the backend. In my server.js file, I have the following code
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
I recently discovered that there is http2 available, should I change the line 3 to
const server = require("http2").Server(app); instead?
If I switch to http2, is there anything else I need to specifically change that wasn't present in http1? And is the way of sending HTTP requests such as get or post any different from http1 to http2?
HTTP2 is more efficient and loads faster pages-Differences.
But I suggest you use https since its more secure and most of the browsers mark non https requests as insecure.
similar stack

Store Cookies at the client side using nodejs

there I am trying to store cookies using the post method using nodejs, cookies are not stored on the browser end currently node server is running on localhost 3001 and react server is running on port 3000
the code what I have written mentioned below
Can anybody please suggest me to fix the issue
const express = require("express")
const app= express()
const cookieParser = require('cookie-parser');
const cors = require("cors")
const port = process.env.port || 3001
app.use(cors())
app.use(express.json())
app.post("/names",async(req, res)=>{
console.log("Ho")
res.cookie("auth","nagendran")
res.json({msg:"Hello"})
})
Edit: Looks like cross origin requests needs quite some work to get cookies right. Take a look here.
Set cookies for cross origin requests

Why combine http module with express module

Hello guys i'm new to node js and started researching and working on some tutorials. I just want a better understanding or clarification on a doubt i had. So i came across the in built module http. This helps in creating a a basic web server. Now express module is a web framework that is built on top the http module that makes it easy using a fully wedged web server without reinventing the wheel. Now I came across this code:
var express = require( 'express' )
, http = require("http")
http.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen(8080);
But in express one could simply just do this
var express = require('express');
var app = express();
app.listen(8080, function() {
console.log('Listening on ' + 8080);});
What's the difference between both? Don't they both accomplish the same thing. If not what's the difference and advantage of using the first approach. Should one adhere to the first approach as it's a good programming practice. That's my doubt as i just want a clear understanding if there's any difference.
Why combine http module with express module
There's really no reason to create your own http server using the http module. Express will just do that for you with app.listen() just fine and save you little bit of typing.
If you were creating an https server, then you would need to use the https module and pass security credentials to https.createServer(...) in order to create a properly configured server. Express does not have the ability to create a properly configured https server for you automatically.
If you look at the Express code in GitHub for app.listen(), it shows this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, there's really no difference (other than a little less typing) when you use app.listen() or create your own http server and then use app as the listener to that server.
So, these two code snippets are identical in function:
var app = require('express')();
app.listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
The above code is functionally identical to:
var http = require('http');
var app = require('express')();
http.createServer(app).listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
Of course, if you're trying to set up https servers or add custom options to the .createServer() method, then you will set up your own server first and then pass app to it as the listener. app.listen(...) is just a shortcut when the default http.createServer() works fine.

Making requests to a node API from a different domain using HTTPS

I am serving a static page over HTTPS (https://example.com) that makes requests to a node API on a different domain (example-api.com).
My API is a standard express app using HTTP. Here's my setup code:
var express = require('express');
var app = exports.app = express();
var port = process.env.PORT;
exports.server = require('http').createServer(app).listen(port);
In the requests from my static page, I specify https://example-api.com as the URL. This works most of the time, but every once in a while (10% of the time?) Chrome errors out on the requests with:
net::ERROR_INSECURE_RESPONSE
Other users who've come across this issue (e.g. Failed to load resource: net::ERR_INSECURE_RESPONSE socket.io) seem to solve it by adding a credentials option to their createServer call, e.g.
var server = https.createServer(credentials, app)
So when I tried to implement this I came up with the following:
var fs = require('fs');
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
var express = require('express');
var app = exports.app = express();
exports.server = require('https').createServer(options, app).listen(port);
However this solution doesn't seem to work for me. When I try it the requests never make it to my app - even logs in app.use middleware don't appear.
What's really confusing is the fact that my setup seems to work most of the time.
Does anyone know how I can reliably make my requests?
Thanks and sorry in advance for my ignorance.
I struggled with this a bit as well. If you are on windows I have a solution that is a bit of a work around, but will allow you to serve your site, and NodeJS app over HTTPS.
In Windows, I created a reverse proxy in IIS to point at the nodeJS RESTful endpoint (i.e. nodeJS RESTful services == website.com:7000). Don't let reverse proxy scare you, its gravy.
To Implement:
Install IIS (if you haven't already)
Create your Self Signed Cert (assuming you know how to do that), or apply your Cert you are using now.
Install Application Request Routing
Open your website configuration, and go to URL Rewrite
For the rewrite stuff:
For Pattern: ^api(.*)
For rewrite: http://www.website.com:7000{R:1}
This basically takes any request from: https://www.website.com/api/someApiAwesomeness, and rewrites it to your nodejs App running at http://www.website.com:7000. Now you have an SSL RESTful app..
Good luck man I hope this helps!

Resources