fabiochiu/medium-articles huggingface dataset:
Functional API in Node.js without external libraries. 👦
By: Pablo Ruiz Ponce
Tags: Nodejs, API, Software Development, Expressjs, JavaScript

👦 Junior developer: To understand this post you don’t need to be an expert but you must be familiar with concepts like: Node.js, API and HTTP.

The motivation for writing this post is because this would have been very useful for me a month back. I’m enrolled in a subject called Web Services and Middleware and on this subject we were supposed to create an API from scratch.

We were free to use any programing language, but there was a restriction: “If you use Node.js, it is not allowed to use Express”

At first, I thought that this task was going to be very easy, but after a few minutes surfing the web I’ve realized that I was wrong. Most of the examples that you can find are based on Express and the few ones that use the HTTP library were extremely basic. This post helped me a lot but it still not enough.

The complete code is right below and during this post I will decompose it and I will explain each part.

This API is based on a customer service. The end users are able to get all the customers and their orders, get detailed information from an specific customer and their orders, add customers and add orders.

The first part of our code must be the HTTP Server where the API will be running. The server has a callback function inside where we will handle everything. This function has 2 parameters:

req - The HTTP request of the client

- The HTTP request of the client res - The HTPP response that the server will provide to the client

Now, if you execute your code, the server will be running in your localhost using the port 3000. At this point, if we go to to localhost:3000/ you won’t see anything. This is because we don’t have the logic of the API yet.

After setting up the server, I like to define all the routes and methods allowed by the API. In Express the routing process is absurdly easy. On the other hand, using just the http library makes the things a little bit more trickier.

For the endpoints the best solution and the one I use is regex. You can also use just the url of the request, as I do on the root, but you will have troubles when defining more complex routes.

For the allowed HTTP methods I use the parameter method of the request

Now your API is almost ready. The last thing you have to do is adding all the rest of the logic, the headers of the response and the actual response of the server. For doing that you have the following methods and attributes:

res.statusCode - Attribute to set the status code of the response

- Attribute to set the status code of the response res.setHeader() - Method to set HTTP headers on the response

- Method to set HTTP headers on the response res.write() - Method to add response data

- Method to add response data res.end() - Method to end the response and send it to the client

That’s all for my first post in Medium. I hope everything of the explained is clear. If you have any doubt or you think that something can be improved in my implementation, write a comment please.
Build a TODO app in less than 5 minutes in Node/Express
By: Faraz Ahmad
Tags: Nodejs, Express, Knexjs, Expressjs, Objection Js

Getting Started

Okay, so let’s dive into the delicious cloud of development ;)

Step 1: Project bootstrap

Create a new directory hello-todo in your working machine.

in your working machine. Open this directory in Visual Studio Code (VSCode) and bring its integrated terminal.

Next, copy and run the following command

npx express-generator

This will generate an express-starter app for you with all the directories and start-up code set up for you in seconds.

Now run npm install to install all the dependencies mentioned in the file. After all the dependencies have been installed, you can run npm start and visit the newly created Express App at localhost:3000 .

Step 2: Set up the CRUD Generator

Create a new directory db in the root of your project.

in the root of your project. Create another directory schemas inside db .

inside . Now create a todos.json and a users.json file inside db/schemas the directory, and paste the below codes into respective files.

The interesting part starts here. Run dricup-crud-express command in the terminal and see the magic. It will create Migration, Model, Controller, and Routes for the todo’s along with some configuration files.

Step 3: Configure Database

The command dricup-crud-express above has created an knexfile.js in the root of the project.

Open it up and add your database details for development environment/key.

environment/key. Run knex migrate:up to run migrations.

Step 4: Update `app.js` file and restart server

Open the app.js file and add the following two lines to it

var todosRouter = require("./routes/todos"); app.use("/todos", todosRouter);

Now close the server (if it is already running) and run the command npm start .

Step 5: Enjoy the App using Postman

Open postman, and you can create/read/update/delete the todos :)
How to create a simple Web Application using Express
By: Simeon Olabode
Tags: Nodejs, Web App Development, Node, Web Development, Expressjs

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It provides developers with a myriad of HTTP utility methods and middleware which makes creating a robust API is quick and easy. There are many popular frameworks that are based on Express.

Installing Express

Before installing Express, it is assumed that you have already installed Node.js. Next, you create a directory to hold your application, and make that your working directory.

$ mkdir myapp

$ cd myapp

Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.

$ npm init

You will be prompted for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)

Enter app.js , or whatever you want the name of the main file to be. If you want it to be index.js , hit RETURN to accept the suggested default file name.

Now install Express in the myapp directory and save it in the dependencies list. For example:

$ npm install express --save

To install Express temporarily and not add it to the dependencies list:

$ npm install express --no-save

Creating a simple Web Application

Let’s create a simple Express App. It is a single file app — not what you’d get if you use the Express generator, which creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and sub-directories for various purposes.

const express = require(‘express’)

const app = express()

const port = 3000 app.get(‘/’, (req, res) => {

res.send(‘Hello World!’)

})

console.log(`Example app listening at

}) app.listen(port, () => {console.log(`Example app listening at http://localhost:${port}` })

This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.

The example above is actually a working server: Go ahead and click on the URL shown. You’ll get a response, with real-time logs on the page, and any changes you make will be reflected in real time. This is powered by RunKit, which provides an interactive JavaScript playground connected to a complete Node environment that runs in your web browser. Below are instructions for running the same app on your local machine.

Running your app locally

First create a directory named myapp, change to it and run npm init. Then install express as a dependency, as per the installation guide.

In the myapp directory, create a file named app.js and copy in the code from the example above.

Run the app with the following command:

`$ node app.js`

Then, load http://localhost:3000/ in a browser to see the output. Your output should be something like this:
EJS In Node.js Template Example
By: Zoran Kuzmanovic
Tags: Nodejs, Expressjs

What is EJS?

EJS is among the most popular template view engines for node.js and express.js.

EJS simply stands for Embedded Javascript. It is a simple templating language that lets users generate HTML with plain javascript.

When to use EJS?

EJS is mostly useful whenever you have “dynamic” content on site and you want to display it. The best example is for online shops. Knowing that your product informations are stored in database. So, from database you are taking that informations and with the help of EJS displaying it on the web page. That proccess is called “dynamic” because you are manipulating with data.

Basic EJS syntax:

<% ‘Scriptlet’ tag, for control-flow, no output

<%= Outputs the value into the template (HTML escaped)

<%- Outputs the unescaped value into the template

EJS template quick start

This is the base(layout). This way you run EJS as your main view engine:

1. First install express.js and ejs from npm. You do it this way:

npm install express ejs

2. Second create app.js and paste next code:

app.js

const express= require(‘express’);

const path= require(‘path’);

var app=express();

//run EJS

app.set(‘views’,path.join(__dirname,’views’));

app.set(‘view engine’,’ejs’); // run EJS

app.get(‘/’,(req,res)=>{

res.render(‘index’,{myVar:37});

})

app.listen(3000);

The last but not least in the main folder create new folder named views and there new file index.ejs

EJS — Views folder

index.ejs

<h1> Hello From EJS : <%= myVar %> </h1>

That’s it. Now you are ready to start playing with EJS.

Down are EJS syntax rules you must follow to use it at its best:

- Passing Variables In EJS

To pass a variable in EJS you need two things:

app.js

app.get(‘/’,(req,res)=>{

res.render(‘page_to_render’,{ key:value });

})

And in your page_to_render include the variable you have put in key:’value’

page_to_render



<h1> <%= key %> </h1>

When we request ‘/ ‘ ,it will redirect us to the ‘page_to_render’ with the object. And in ‘page_to_render’ we output that value.

- If Else Statements with EJS

index.ejs

<h1>Hello World

<% if(1+1===2){ %>

<p>It’s 2</p>

<% }else{ %>

<p> It isn’t 2 </p>

<% } %> </h1>

In this example we have used <% … %> instead of <%= …%> , because if statements use <% … %> . When you want to pass EJS variable you will use <%= … %> (previous example)

- Including Partials With EJS

To include partials in EJS you need to create folder ‘partials’ and there partial file. My partial file is named ‘hello.ejs’

hello.ejs

<h1> Hello From EJS</h1> and now include the file in index.ejs :

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body> <%- include(‘./partials/hello.ejs’) %> </body>

</html>

And yes you use <%- %> to include partials in EJS.

- Loop Through Objects With EJS Loops

index.ejs

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body> <% var obj={name:’John’,age:20, country:’Russia’};

const objValues= Object.values(obj);

for(let i of objValues){ %>

<h1> <%= i %> </h1>

<% } %> </body>

</html>

Also with loops, we are using control-flow EJS tags!
Adding Nuxt to an existing Express service
By: Vladimir Kraykin
Tags: Nuxtjs, Expressjs, Server Side Rendering

Well, usually you do completely the opposite. But maybe there is another developer that is looking for this tutorial, as I was.

Why?

Before moving further, I would like to explain why I needed it. If you already have your own reasons then just skip this part.

At my company we have a PaaS team that maintains a service for creating internal services (yeah tautology…). Why so? It reduces a significant amount of time when creating a new service. You get a fully configured Express template on GitHub with already enabled CI/CD and all the internal dependency packages within a few minutes. So it was more natural to add Nuxt to an already existing Express service, rather than using create-nuxt-app and configuring serverMiddleware from scratch.

How?

Let’s start by creating our app. Open terminal and choose a folder to work in.

mkdir nuxt-as-express-middleware; cd nuxt-as-express-middleware

Initializing the app.

npm init

Installing dependencies.

npm i express nuxt

Creating the heart of the app.

touch app.js

Open app.js in your favorite editor and copy-paste this code.

Well, that’s it. But if you’re interested in what is going on here let’s dig a bit deeper.

loadNuxt first searches for nuxt.config.js if it doesn’t exist Nuxt uses default configurations. After loading the configurations it creates and returns an instance of Nuxt.

nuxt.render is a classical middleware function which maps Express requests to Nuxt routes. Because this function will handle the rendering of your web application and won’t call next() you should call it at the end of your middlewares.
EJS In Node.js Template Example
By: Zoran Kuzmanovic
Tags: Nodejs, Expressjs

What is EJS?

EJS is among the most popular tempate view engines for node.js and express.js.

EJS simply stands for Embedded Javascript. It is a simple templating language that lets users generate HTML with plain javascript.

When to use EJS?

EJS is mostly useful whenever you have “dynamic” content on site and you want to display it. The best example is for online shops. Knowing that your product informations are stored in database. So, from database you are taking that informations and with the help of EJS displaying it on the web page. That proccess is called “dynamic” because you are manipulating with data.

EJS template quick start

This is the base(layout). This way you run EJS as your main view engine:

1. First install express.js and ejs from npm. You do it this way:

npm install express ejs

2. Second create app.js and paste next code:

app.js :

const express= require(‘express’);

const path= require(‘path’); var app=express(); //run EJS

app.set(‘views’,path.join(__dirname,’views’));

app.set(‘view engine’,’ejs’); // run EJS app.get(‘/’,(req,res)=>{

res.render(‘index’,{myVar:37});

}) app.listen(3000);

The last but not least in the main folder create new folder named “views” and there create index.ejs file:

index.ejs :

<h1> Hello From EJS : <%= myVar %> </h1>

That’s it. Now you are ready to start playing with EJS.

Here is complete EJS tutorial series, short and easy to understand:

https://www.youtube.com/watch?v=IqpfBGsALqc&list=PL7sCSgsRZ-slYARh3YJIqPGZqtGVqZRGt
Create Hello World in Expressjs
Tags: Nodejs, Hello World In Expressjs, Expressjs Webdevelopment, Expressjs Development, Expressjs

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

1. Installation

1.1 Install Nodejs

You need to install Nodejs in your system. If you have not installed, you can install from below url:

1.2 Check version after installation

Open command prompt and type below commands to check node and npm version.

node -v

npm -v

2. Create project

2.1 Go to project folder and create directory

F:\javascript-projects\express-projects

mkdir myapp

cd myapp

For example, this is my project folder is F:\javascript-projects\express-projects.

2.2 Create package.json

npm init

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit ENTER key to accept the defaults for most of them, with the following exception:

2.3 Now install Expressjs

npm install express — save

2.4 After installation project folder

3. Create Hello World

3.1 Create src folder inside that index.js file

It is not necessary to create src folder. You can create index.js in root project folder also.

3.2 Open index.js file and write below code

//include express module or package

const express = require('express'); //create instance of express

const app = express(); app.get('/', (req, res) => res.send('Hello World'));

app.listen(4000, () => console.log('Listening on port 4000!'));

This app starts a server and listens on port 4000 for connections. You can run on different port also like in 3000. The app responds with “Hello World!” for requests to the root URL (/) or route.

Save the file.

4. Run the project

4.1 Type below command in terminal

In this project index.js file is inside src folder, so need to write like “node src/index.js”. If your index.js file is in root project folder, then directly you can run command “node index.js”.

node src/index.js

4.2 View in browser

http://localhost:4000/
Add Docker to your NodeJS workflow with 4 simple steps
By: Kristian Roopnarine
Tags: Nodejs, JavaScript, Docker, Expressjs, Programming

What is Docker and why should you use it?

Docker is a platform as a service which allows you to isolate an entire operating system via Linux containers. The files we create below are instructions for how Docker should build the Linux container. Dockerizing (is that a word?) your application should be the first step in your workflow as it provides a good base for your development and production environments. Onboarding new members to the project is easy too, just provide them the respective Dockerfile and they’re good to go. Docker can become extremely complicated and you can add a lot of configuration to your application with Docker alone.

Y ou will definitely benefit from spending time researching complex features of Docker!

Add Docker to your NodeJS apps in 4 steps

I don’t explain what the following code does, but docker has great documentation on it, https://docs.docker.com/engine/reference/builder/ .

All of the following config files will be at the root of your project. These files will work for probably 90% of your NodeJS applications, barring specific configuration.

If this is an application that will be shipped to production, create a separate Dockerfile.prod that contains configuration for your production application. These config settings can be googled because there are many people who have used Docker in production. This helps separate dev vs prod configuration with ease.

Create a Dockerfile.dev and add the following code

Docker image config

2. Create a docker-compose.yml and add the following config

docker-compose config

3. Create a .dockerignore and add node_modules to it. This speeds up your build times because Docker will not copy over the node_modules into the Docker container. Instead Docker builds node_modules when running npm install . Add other files/directories you do not want to be copied into your docker container here!

4. Execute the following commands in the root directory of your project, depending on what you need:

docker-compose up -d --build : Builds the container using Dockerfile.dev and starts your docker container in detached mode

: Builds the container using and starts your docker container in detached mode docker-compose up -d Starts your docker container in detached mode

Starts your docker container in detached mode docker-compose down ALWAYS run this command when stopping your container

run this command when stopping your container docker ps Lists your current active containers
NodeJs Real-Time Execution Monitoring with Inspector
By: Valerio Barbera
Tags: Nodejs, Node Js Tutorial, Expressjs, Monitoring

Have you ever desired to watch your code running, instead of just imagining it?

Hi, I’m Valerio software engineer from Italy and CTO at Inspector.

As product owner I learned on my skin how an application issue can be so hard to fix, creating a negative impact on the users experience, or block new potential customers during on-boarding.

I publish new code changes almost every day and unfortunately it’s quite impossible to anticipate all the problems that could happen after every release. Furthermore users don’t spend their time reporting bugs, if something goes wrong they just stop using our application, looking for another one that fits their needs better.

When I started to share my idea behind Inspector I realized that many developers know the problem: they spend a lot of time to investigate strange behaviors inside their application, but they didn’t know that there’s a solution to eliminate this complexity in two minutes, avoiding customer complaints or even the loss of the customer.

Inspector is an npm module to add real-time code execution monitoring to your NodeJS application, allowing you to work on continuous code changes while catching bugs and bottlenecks at a glance before users do.

In this article I’ll use Express framework to build code snippets, but you are free to use Inspector in any Nodejs script.

Read the original article: https://inspector.dev/nodejs-real-time-execution-monitoring-with-inspector/
Uploading Files using Multer in Node.js Applications
By: Bewar Salah
Tags: Nodejs, Multer, API, Expressjs, JavaScript

Uploading Images Using Multer

Table of Contents

Introduction

Today, we can find many apps and websites that upload images like photo sharing apps or blog websites. That is why, there are many good reasons to allow users store files on server. Http servers handle file uploading using POST requests. The case is different while talking about node.js. It is hard for node.js alone without using a library to handle uploading. That is the reason, there are many npm packages available. Multer is a good uploading npm package. It is mainly used with express.js.

Building web APIs is easy with Express.JS. I have already posted a tutorial about express.js. Multer is a npm package that handles multipart/form-data. It enables express.js applications to accept files. It is very easy to configure in express.js servers. This blog is minimized to teach only file uploading using multer, however it tries to give you a clue on how to link an image to a record in database and retrieve it later.
Create and Deploy a Node.js/Express App with UI for Free with Vercel
By: Duc N.
Tags: Nodejs, Zeit, Vercel, Web Development, Expressjs

Create and Deploy a Node.js/Express App with UI for Free with Vercel

Disclosure: I have no affiliation or investment in any company mentioned in this post. This is just my experience.

I assume you have some experience with Node.js, Express and have signed up for a free Vercel account.

Vercel (zeit) has been working fine for me for a while. The problem is there are different ways on the internet to set it up and most of them doesn’t work for me anymore, maybe due to changes from Vercel. But I’m glad this setup works now.

Github repository link:

- https://github.com/ngduc/vercel-express

First, clone the above repository to a local directory. Set up vercel command line and run “vercel” command to deploy the project:

Set up & Deploy with Vercel

$ npm install vercel -g $ cd <project-dir>

$ npm install

$ vercel

Vercel will generate a “.vercel” directory, don’t share or commit this one.

After deploying, open your URL that looks like this:

— http://YOUR-VERCEL-APP-ID.vercel.app

— Example: https://vercel-express-3.ngduc.vercel.app

app/index.js

If you’re using Typescript with node, build your source directory (using a tool like “tsc” command line from “typescript” package), output to “app”.

Update package.json: “main”: “app/index.js”

vercel.json

Map API routes (/api/…) and static (UI) routes (/…).

Now you have a full-stack web application deployed to the Internet using Vercel!

Happy coding!

Links:

- This official article describes more in details about Vercel and Express — https://vercel.com/guides/using-express-with-vercel

- Github Repo — https://github.com/ngduc/vercel-express
How to Use Tailwind CSS With Node.js, Express, and Pug
By: Catalin'S Tech
Tags: Nodejs, Tailwind Css, Programming, Expressjs, JavaScript

Project Configuration

The first step is to create and configure our application. Run the following commands to create an empty directory called nodejs-tailwind and change the current directory to it:

mkdir nodejs-tailwind

cd nodejs-tailwind

Now that we are in the nodejs-tailwind directory, we have to initialize our Node project. To do so, we need to run the following command:

npm init

For each Node project, we need a file called package.json . Its purpose is to store metadata about the project (e.g. name, description, version, author, etc.) and manage the project dependencies and scripts. We could create the file manually, but that would be tedious.

Thus, the purpose of npm init is to create the package.json file. Once you run the command, you get an interactive prompt where you can add information about your project. Or, if you are happy with the suggested information, you can press enter until the end. If you do not add any information, your file should look like this:

Now we need to create the index.js , which stores our basic server. You can create the file by running:
A journey from big to badaa…
By: Shubham Kumar
Tags: Mern, Fullstack Development, Masai School, Expressjs, React

This is all about the outcome of 30 weeks of rigorous training at Masai School. The course is about to end but now the real journey is going to start. Today we have completed our final project or you can say the first project of our professional career. In our final project, we tried to clone bigbasket.com. It was a 14 days long project and we had started it from scratch. And here you can see the final visuals @ badaabasket.tk.

Starting from Day-1, we were the team LIME with 3 members in our team (Soumitha, Sanjay, Shubham). We spent whole day on planning how we should proceed and from late night we started coding. By the end of Day-3, we had our landing page ready and on day-4 we had implemented OAuth. There used to be two standups which use to happen everyday and on Day-6 before standup we got some major merge conflict and we needed to update everyday’s progress but finally we were able to resolve the conflict before standup. By the end of Day-8 we had completed the order flow as expected. On Day-10, we implemented payment integration. Now almost everything was in place and we started to clean up the UI and at the end of Day-12 we had completed our testing also. Now major challenge was to deploy our website on AWS because no one in our team knew about it. So, we started to learn that and it took more than 36 hours to understand it. Now at the end of Day-14 our website was deployed.

landing page visuals

Major learning from this project would be that as a team we can do a whole lot better than as an individual. This was the first time we all were doing this kind of end to end project and cherry on the cake it was a virtually collaborative project and It was a great experience.
Node.js Express Word Docx to PDF Converter App Using LibreOffice Library Deployed to Website
By: Coding Geeks
Tags: Coding, Nodejs, Tools, Expressjs, Programming

Node.js Express Word Docx to PDF Converter App Using LibreOffice Library Deployed to Website

Hi friends today in this blog post we will talk about my online converter app that I developed using node.js and express which is docx to pdf converter which is deployed on my website
THE CONCEPT OF ROUTING AND MIDDLEWARE IN EXPRESS.js
By: Edet Noah
Tags: Nodejs, Backend Development, Middleware, Expressjs, JavaScript

MIDDLEWARE IN EXPRESS

Express middleware are functions that execute in-between the lifecycle of a request to the Express server and which also have access to req and res methods.

const app = require("express")(); const PORT = 2000; app.get("/", (req,res) =>{ res.send("welcome to my homepage!!!!!!"); console.log("welcome page"); }); app.listen(PORT, ()=>{ console.log(`APP IS RUNNING ON PORT ${PORT}...`); });

So from the code above, we can say the function with (req and res) is a middleware..

let’s see middleware in Express as a bridge between one layer and another.

Okay, that’s the basis.. lets dive in

Lets create our own middleware, like we already know by now that a middleware is a function that has access to req and res method.

from the code above we’ve created a function logger which has access to the req and res methods.. YEAH that’s a middleware!



Okay, now we have to tell Express we want to make use of that middleware, to do so we make use of app.use('middleware_name') in this case our middleware name is ‘logger’. So its going to be app.use(logger)

WE DON”T HAVE TO CALL IT AS A FUNCTION app.use(logger()) . Take note of that.

let’s start our server and see what’s happening

Wow… nothing is displaying

let’s check our terminal

We’re getting respond from our logger middleware but nothing from our “/” route and we are expecting a respond from that route because we are in there.. So what’s happening here?

Express don't know what to do after that respond, we have to tell it! and to do so we make use of the “next” function in Express and what this does is that

It tells Express to run the next middleware.

Next function in express executes the middleware succeeding the current middleware.

In our logger middleware we have to pass in next as a parameter so we can have access to it by calling it as a function in our logger method.

const app = require("express")(); const PORT = 2000; app.use(logger); app.get("/", (req, res) =>{ res.send("welcome to my homepage!!!!!"); console.log("welcome page"); }); function logger(req, res, next){ console.log("log"); next() } app.listen(PORT, ()=>{ console.log(`APP IS RUNNING ON PORT ${PORT}...`); });

So let’s start our app and visit localhost:2000

Yeah, so now everything works as expected.
Routes and Middleware in Node.js/Express, Simplified
Tags: Nodejs, Middleware, Software Development, Expressjs, Programming

What comes into your mind when you hear of routing in an application?

This refers to how an application responds to a request from the client side to a particular endpoint with a specific http request method (POST,PUT,DELETE, etc.), you get it? if not, Don’t worry…

In simple terms, routing refers to how the application behaves on a specific url or path with a specific HTTP method

For example, let’s say you have a 3-page website with URL (http://mywebsite.com), which includes the Home page, contact us page and an about us page,

Just a simple header to display 3 links

so this is where routing comes into play, with a get request to the homepage i.e. (http://mywebsite.com), you intend to respond with the home or landing page where u have these fancy carousel and all making it look great, isn’t it?

Credit to @uiraygan on IG for the awesome UI design

but for a get request to the URL (https://ourwebsite.com/contactus), obviously we intend to respond with some sort of form where a user could input details such as email, name and leave a message for us

So with this basic explanation of routing in an application, I hope you get what exactly i am trying to put across…yep!
React Express developement & production on Plesk
Tags: Nodejs, Boilerplate, Expressjs, React, Plesk

In this tutorial we are going to use React Boilerplate to create the app.Also we are going to change some changes to core react boiler plate to fit the app into Plesk server.

Clone Repository

First You have to create a sub domain for developement for react app. Sub domain for developement should be random & hard to guess like password [dev_password].example.com

Create a directory named react and point that folder to sub domain [dev_password].example.com. Now clone React boiler plate repository https://github.com/react-boilerplate/react-boilerplate using git extension or Manually upload entire contents to subdomain.

clone git repository https://github.com/react-boilerplate/react-boilerplate

Now For plesk server, express server file need to be in root directory. So we have to move the index.js file in server folder to root folder of the domain (react folder).

Then update logger, argv , port, serup variables in index.js

const logger = require(‘./logger’);

const argv = require(‘./argv’);

const port = require(‘./port’);

const setup = require(‘./middlewares/frontendMiddleware’);

to below variables, so that it will get files correctly.

const logger = require('./server/logger');

const argv = require('./server/argv');

const port = parseInt(process.env.PORT || '3000', 10);

const setup = require('./server/middlewares/frontendMiddleware');

Now create file .npmrc in react folder. Now open that file and past below contents to that file

scripts-prepend-node-path=true

This .npmrc file is used to run scripts in package.json for plesk environment.

Now create a public folder in react folder. This public folder should not contain index.html file. This folder will serve the static files, but it is actully not used by react boilerplate.

All these changes to react boilerplate are made in github repository https://github.com/muthu32/react-boilerplate

Development Server

Now open nodejs extension page for domain. Now Change Document Root to folder react/public and Application Root to react. Also change Application Mode to developement and Application Startup File to index.js. Finally click on "Enable Node.js" button in Node.js extension for subdomain.

Plesk node.js extension for development server

Now press on "Run Script" button in Node.js extension for subdomain. Here you can run scripts defined in package.json file. This button is also used to build our app and setup the app. Enter setup in Script name and parameters field and press Run to set up our app. After running setup script, node_modules folder will be created in root folder of subdomain. Here all our npm dependencies will be stored for the app.

setup domain using Run Script

Now open Applicaiton URL [dev_password].example.com to view our Development app. Upon updating components in react/app/components, our app will automatically reload on [dev_password].example.com (Hot Reload)
How to create a Node.JS application with Express.JS
By: Deepak Sharma
Tags: Nodejs, Node Js Tutorial, Express, Node, Expressjs

1.) What is node.JS and express.JS?

Node.js is cross-platform runtime environment to build network application. Node.js is designed to build scalable real time applications using JavaScript on server-side. Node.js was developed by Ryan Dahl in 2009. It is free and open source, means its source code can inspect, modify, and enhance by anyone.

Express.js is a back-end web application framework for node.js and it is used to build small as well as large web application using node.js runtime environment. Express.js is free and open source software under MIT license.

2.) Setup node.js application on Linux OS:

First, make a separate new directory for your application using command:

$mkdir nodeBackEnd

Then go to this folder and initialize your project by npm init:

$cd nodeBackEnd $npm init

(Before using npm make sure NodeJS should installed on your system with npm software library.)

After executing npm init command follow these steps:

Example:

a.) package name: nodeApp b.) version: default c.) description: for test use only d.) entry point: server.js e.) test command: default f.) git repository: default g.) keywords: default h.) author: default i.) license: default j.) is it okay: yes

Above steps of initializing project is completely user dependent. You can modify those steps as per your application need.

Now you can see a package.json is created in nodeBackEnd folder with specification you provided during your application initialization process.

It is time to create a new file called server.js in same folder: nodeBackEnd

$touch server.js

3.) Paste the below code in file server.js:

const express = require(‘express’) const app = express() const PORT = process.env.PORT || 3001; const server = app.listen(PORT, () => { console.log(‘Express server running on port ‘ + server.address().port) });

4.) Now install packages like express that used in server.js file using command:

$npm install express

(Install other packages by replacing the package name in above command)

5.) Start node.js server:

Now it is time to up node server using command:

$node server.js

Or
Setup Nodemailer 2020
By: Tanuj Choudhary
Tags: Nodejs, Nodemailer, Mail, Expressjs, Oauth

This tutorial shows how to setup nodemailer and send mails using node js.

Prerequisites:

Node js

Basic knowledge of Google Console

Step 1: Create a simple node or express server

Step 2: Create Client ID in Google Console

Go to https://console.developers.google.com/

Login or create a account

Create a project and select it.

Go to API & services → Credentials → Create Credentials → OAuth Client ID

Choose web application

Enter “https://developers.google.com/oauthplayground” in Authorized redirect URIs.

Copy your client ID and client Secret.

Step 3: Get refresh_token

Go to https://developers.google.com/oauthplayground/

Go to right corner. Click on settings. Enter your client ID and client secret

On left of page. Enter “ https://mail.google.com/” and click on Authorize APIs

Click “Exchange authorization code for tokens” button.

Congrats! You got your refresh token

Step 4: Lets see the code

Open your terminal in project directory and run

npm install googleapis

Create a file named oAuth2Client.js

const { google } = require('googleapis');

const { OAuth2 } = google.auth; // Reusable client const oAuth2Client = new OAuth2(

'Your Client ID',

'Your Client Secret',

'https://developers.google.com/oauthplayground'

);

oAuth2Client.setCredentials({

refresh_token: 'Your refresh token',

}); module.exports = oAuth2Client;

Create a file named nodemailer.js

const nodemailer = require('nodemailer'); const oAuth2Client = require('./oAuth2Client');

const accessToken = oAuth2Client.getAccessToken(); const smtpTransport = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: 'Your OAuth Email', // Your gmail address clientId: 'Your Client ID', clientSecret: 'Your Client Secret', refreshToken: 'Your OAuth refresh token', accessToken: accessToken, }, }); module.exports = smtpTransport;

Import nodemailer in file where you want to use it

const nodemailer = require('./nodemailer'); // Mail options

const mailOptions = {

from: 'SENDER_EMAIL',

to: 'RECEIVER_EMAIL',

subject: 'YOUR_SUBJECT',

text: 'YOUR_MESSAGE',

}; // Send mail

nodemailer.sendMail(mailOptions, () => {} ); // Close

nodemailer.close();

That's it.

Thanks for reading.
Express Validator
By: Kirill Chaim Shcherbina
Tags: Expressjs

Photo by Brian McGowan on Unsplash

Express validator is one of the many npm packages for validating a request an express application.

I recently used express validator in a project and stumbled upon a few challenges which I'm going to share in this article.

When you visit the express validator docs, you’d notice the way the validator was used in the examples as shown in the snippet below:

const { check, validationResult } = require('express-validator') app.post(

'/user',

[

// username must be an email

check('username').isEmail(),

// password must be at least 5 chars long

check('password').isLength({ min: 5 }),

],

(req, res) => {

// Finds the validation errors in this request and wraps them in an object with handy functions

const errors = validationResult(req)

if (!errors.isEmpty()) {

return res.status(422).json({ errors: errors.array() })

} User.create({

username: req.body.username,

password: req.body.password,

}).then(user => res.json(user))

}

)

Looking at the snippet above, you will notice that the validation is tightly coupled to the route definition. That pattern may be good for a simple case but when it comes to scaling, it will be difficult for the code to be maintained and it will make reading the routes difficult.

To make the validation be more readable and easier to maintain:

Step 1

Create a file named validator.js

Inside the validator.js , we are have two functions, one of the functions will hold the validation rules, while the second will contain the function the does the actual validation.

const { body, validationResult } = require('express-validator')

const userValidationRules = () => {

return [

// username must be an email

body('username').isEmail(),

// password must be at least 5 chars long

body('password').isLength({ min: 5 }),

]

} const validate = (req, res, next) => {

const errors = validationResult(req)

if (errors.isEmpty()) {

return next()

}

const extractedErrors = []

errors.array().map(err => extractedErrors.push({ [err.param]: err.msg })) return res.status(422).json({

errors: extractedErrors,

})

} module.exports = {

userValidationRules,

validate,

}

Step 2

Now re-writing the initial snippet above, we have:

const { userValidationRules, validate } = require('./validator.js')

app.post('/user', userValidationRules(), validate, (req, res) => {

User.create({

username: req.body.username,

password: req.body.password,

}).then(user => res.json(user))

})

Now if you try to register a user without meeting the specification for the user data, the validation error response would look like shown below:

{

"errors": [

{

"username": "username must be an email"

},

{

"password": "password must be at least 5 chars long"

},

]

}

Conclusion

With this method in place, you can define the validation rules for each route or module in a separate file as you may deem fit and then chain it with the validate middleware . That way the code looks much cleaner, easier to read and easier to maintain.

Hope you enjoyed reading!
Catch ExpressJS Async Errors
By: Dak Washbrook
Tags: Expressjs, Asynchronous, Async, Express

If you tried or happened to throw an error from within an async express route handler then you are probably looking at an error that looks like this:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with.catch(). (rejection id: 1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Trying to find the cleanest solution to this has led me to quite a few places that offer the following solutions:

Wrapping all request handler logic in try / catch blocks to pass the caught error to the next() function

/ blocks to pass the caught error to the function Wrapping every request handler inside a function that checks if the handler is an async function to further wrap it with a .catch(next) .

You can see both of these explained here: https://zellwk.com/blog/async-await-express/. These are both viable solutions. Though, I wanted to seek out a way to do this passively instead of actively.

This is what led me to utilize JavaScript’s native Proxy built-in:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)

Used in tandem with the handler.apply() method, explained here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply.

Below is a singular simple patch to fix this issue, without having to do anything with each async request handler.

const Layer = require('express/lib/router/layer')



Object.defineProperty(Layer.prototype, 'handle', {

set: function (handle) {

this._handle = new Proxy(handle, {

apply: function (target, thisArg, argumentsList) {

const type = target.constructor.name

if (type === 'AsyncFunction') {

const wrappedFunction = (...args) => {

const next = args[args.length - 1] || Function.prototype

target.apply(thisArg, args).catch(next)

}

wrappedFunction(...argumentsList)

return

}

target.apply(thisArg, argumentsList)

return

}

})

},

get: function () {

return this._handle

}

})

Import or run this piece of code upon server startup and it will patch express.

There is a very similar version of this here https://github.com/davidbanham/express-async-errors/blob/master/index.js as well.

Let me know your thoughts in the comments below!
Single & Multiple image upload in NodeJS(ExpressJs) using Multer to Cloudinary(MVC)
Tags: Nodejs, Multer, Mongoose, File Upload, Expressjs

Today we are going to learn how to upload multiple images to cloudinary.We start by creating an expressjs server and pass in cors configuration options,connect to MongoDb using mongoose and we will create a route where we will configure multer and pass multer as a middleware in the route.

We will Follow MVC Pattern

This is main Js file is named app.js,below is the code for app.js,we create an express app with cors configuration.

We create an express app with a route where we will configure multer to intercept the images

We configure multer with the memory storage option and add the middleware to the route ‘/car’

We will write 2 helper functions 1 for cloudinary upload and another one for data uri-this will convert the buffer to base64format

Cloudinary helper function

Data uri helper function

We are going to use mongoose to store the urls in the database,We will go with a car example.We will define an Array schema for the links fields

We will start with single image Upload,as defined below in the controller

We import sharp,car model,datauri helper function and cloudinary helper function

We get the image buffer from req.files.imagecover[0].buffer(note:the name imagecover must match the routes multer.fields() configuration,we get the buffer resize it with sharp convert it to jpeg enhance the quality and then convert it to buffer again.we then use the datauri helper function to convert the buffer of the modified image to base64 format so that we can upload it to cloudinary.The data uri function will return an object we need the content part we will use async await to upload the file.We await the result push the link to an array.For multiple images …………………………

With the same imports we initialize 2 Arrays one for the links one for the resized image buffer.

We use a for loop to loop through req. files.gallery(note:we use gallery because of multer configuration in the routes section when we wrote the code as-These keys are important when accessing the intercepted files

upload.fields([{ name: “imagecover”, maxCount: 1 },{ name: “gallery”, maxCount: 4 },]),

We loop through the array and resize each image buffer,convert to jpeg,then push to the resized buffer array,after that we use for of (because we need to use async await in the loop is possible for for of loop),we use data uri in a for of loop to convert each buffer to base64 format,we then use the content returned by the data uri helper function to upload all images in the loop,we then push the links to the imagegallery array

we then match the arrays with variables to store in mongoose database.

We finished this section lets send a request in postman we see what we get

This is how the req will look like remember to use the keys you specified when configuring multer as a middleware.

We finally get a response from the api with the links in position
Build a JSON API app with Node.js & Express.js — Step-by-step Guide
By: Kanan Rahimov
Tags: Json Api, Nodejs, Expressjs, Tutorial

In this video tutorial, my goal is to create an example Node.js backend API which can be used for React / Next.js projects. API will return a JSON response.

The thing is most of the parts of React / Next.js projects require working backend API so you can fetch data. It’s relatively easy to do so in Python or Golang. Usually with a few lines of code. In this coding session, I want to explore for myself if it is the same in Node.js.

Since it is a coding session and a video-post at the same time, on this page I will post the process, which might contain a lot of “progress content.” If you want to see the result and just a short explanation, jump to the end of the page.
ReferenceError: window is not defined
By: Debender Prasad
Tags: Nodejs, Typescript, Mxgraph, Server Side Rendering, Expressjs

Import domino ()// As the name might suggest, domino's goal is to provide a DOM in Node.

when using the ts-mxgraph wrapper for mxgraph, the headless chromium from the server doesn't get a browser window and that's where the below patch can rescue.

const win = domino.createWindow(template);

create a dummy global window and other stuffs as you need from the below list.

global['window'] = win;

global['document'] = win.document;

global['DOMTokenList'] = win.DOMTokenList;

global['Node'] = win.Node;

global['Text'] = win.Text;

global['HTMLElement'] = win.HTMLElement;

global['navigator'] = win.navigator;

Now the below code should work

import {mxgraphFactory} from 'ts-mxgraph';

const mx = mxgraphFactory({

mxBasePath: 'mxgraph',

mxLoadResources: false,

mxLoadStylesheets: false,

});