Send POST request to Node / Express.js server with Angular8

In the previous tutorial, we've created authentication (login and register) forms with Angular 7/8 and a RESTful API server for handing authentication with Node and Express.js.

We've created the Login and Register components with the necessary forms to collect the user's credentials (name, email and password) and display them on the browser's console. In this tutorial, we'll add the code for actually submitting user's information to the authentication server in order to register or authenticate the user.

This is the screenshot of the registration component:

This is the screenshot of the login component:

When you click on the login and register buttons, the values your entered on the form will be only displayed on the console but in actual web applications these values need to be sent to the authentication server (in our case it's a Node and Express.js server that's running locally on the http://localhost:3000 address).

Let's change that!

Basically what you need to do it to change the register() and signIn() methods to send an HTTP POST request to the authentication server with Angular HttpClient.

But, we are not going to call the HttpClient methods directly from the register() and login() methods because that's usually considered bad practice in Angular. Instead we'll create an Angular service that encapsulates all the communication with the authentication server.

In nutshell, these are the steps that we are going to follow throughout this tutorial:

  • First, we need to setup HttpClient in our project (exactly in our auth module),
  • Next, we generate an AuthService and we implement methods such as signIn()register() and signOut() etc.
  • Finally, we inject AuthService in out Login and Register components and we call the appropriates service methods to register and authenticate users.

So let's get started!

Prerequisites

As a prerequisite, this tutorial assumes you have followed the previous tutorial where we have created the authentication server with Node and Express.js and created the Angular 8 project with the necessary modules and components.

Setting up HttpClient

Previously we've created the auth module. This module encapsulate the authentication logic in our application. Let's import HttpClient in this module.

Open the src/app/auth/auth.module.ts file and add the following changes:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AuthRoutingModule } from ‘./auth-routing.module’;
import { RegisterComponent } from ‘./register/register.component’;
import { LoginComponent } from ‘./login/login.component’;

@NgModule({
declarations: [RegisterComponent, LoginComponent],
imports: [
CommonModule,
FormsModule,
HttpClientModule,
AuthRoutingModule
]
})
export class AuthModule { }

We simply import HttpClientModule from @angular/common/http and we add it in the imports array of AuthModule.

That’s it! You are ready to send HTTP requests in your application.

Creating AuthService and Injecting HttpClient

Next, let’s create an Angular service that’s responsible for sending authentication requests to the backend server.

In your terminal, navigate to your Angular project’s root folder and run the following command:

$ ng generate service auth/auth

Note: We add the auth/ path before the name of our service (which is also auth) to make the service a part of the auth module.

The command will generate two src/app/auth/auth.service.spec.ts and src/app/auth/auth.service.ts files.

Open the src/app/auth/auth.service.ts file, import HttpClient and inject it via the service’s constructor:

import { Injectable } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;

@Injectable({
providedIn: ‘root’
})
export class AuthService {
constructor(private httpClient: HttpClient) { }
}

Implementing the Authentication Methods

After creating the AuthService and injecting HttpClient let’s now create the methods of the service i.e the register()signIn()signOut() and isAuthenticated() methods. The register() and signIn() methods work by sending POST requests to the /register and /login endpoints of the backend server with the user’s credentials. The server will process the POST requests and create or authenticate the user.

Adding User and JWTResponse Model(s)

We’ll be using two models:

  • The User model that encapsulates information about a user such as name, email and password.
  • The JWTResponse model that encapsulates information about the returned JWT response from the server which contains the JWT access token, the expiration date and the user’s information used to create the token.

In your terminal, run the following commands to generate the User and JWTResponse models:

$ ng generate interface auth/user
$ ng generate interface auth/jwt-response

Open the src/app/auth/user.ts file and update as follows:

export interface User {
id: number;
name: string;
email: string;
password: string;
}

Open the src/app/auth/jwt-response.ts file and update as follows:

export interface JwtResponse {
user: {
id: number,
name: string,
email: string,
access_token: string,
expires_in: number
}
}

Next, open the src/app/auth/auth.service.ts file and import the two models:

import { User } from  ‘./user’;
import { JwtResponse } from ‘./jwt-response’;

Also, import ObservableBehaviorSubject and tap()

import { tap } from  ‘rxjs/operators’;
import { Observable, BehaviorSubject } from ‘rxjs’;

Next add a variable that holds the address of the authentication server:

AUTH_SERVER = “http://localhost:3000”;

Finally, add a authSubject variable of type BehaviorSubject with initial value of false:

authSubject  =  new  BehaviorSubject(false);

This variable tracks the user’s authentication state. false means the user is not authenticated yet.

Adding the register() method: Sending a POST Request with HttpClient

Let’s start with the implementation of the register() method. Open the src/app/auth/auth.service.ts file and add:

  register(user: User): Observable<JwtResponse> {
return this.httpClient.post<JwtResponse>(${this.AUTH_SERVER}/register, user).pipe(
tap((res: JwtResponse ) => {

    if (res.user) {
      localStorage.set("ACCESS_TOKEN", res.user.access_token);
      localStorage.set("EXPIRES_IN", res.user.expires_in);
      this.authSubject.next(true);
    }
  })

);

}

Adding the signIn() Method: Sending a POST Request with HttpClient

Next, add the signIn() method:

  singIn(user: User): Observable<JwtResponse> {
return this.httpClient.post(${this.AUTH_SERVER}/login, user).pipe(
tap(async (res: JwtResponse) => {

    if (res.user) {
      localStorage.setItem("ACCESS_TOKEN", res.user.access_token);
      localStorage.setItem("EXPIRES_IN", res.user.expires_in);
      this.authSubject.next(true);
    }
  })
);

}

Adding the signOut() Method: Removing the JWT Token from Local Storage

Next, let’s implement the signOut() method:

  signOut() {
localStorage.removeItem(“ACCESS_TOKEN”);
localStorage.removeItem(“EXPIRES_IN”);
this.authSubject.next(false);
}

Adding the isAuthenticated() Method: Returning the authSubject as Observable

isAuthenticated() {
return this.authSubject.asObservable();
}

Calling AuthService Methods in The Components

After fully implementing AuthService, let’s now call these methods in the Login and Register components.

Open the src/app/auth/login.component.ts file and update it as follows:

import { Component, OnInit } from ‘@angular/core’;
import { Router } from ‘@angular/router’;
import { AuthService } from ‘…/auth.service’;
import { User } from ‘…/user’;

@Component({
selector: ‘app-register’,
templateUrl: ‘./register.component.html’,
styleUrls: [‘./register.component.css’]
})
export class RegisterComponent implements OnInit {

constructor(private authService: AuthService, private router: Router) { }

ngOnInit() {}

register(form) {
console.log(form.value);
this.authService.register(form.value).subscribe((res) => {
this.router.navigateByUrl(‘home’);
});
}
}

First we import AuthService and Router and we inject them via the component’s constructor. Next, we call the register() method of AuthService and we pass in the form value.

Next, open the src/app/auth/register.component.ts file and update it as follows:

import { Component, OnInit } from ‘@angular/core’;
import { Router } from ‘@angular/router’;

import { AuthService } from ‘…/auth.service’;
import { User } from ‘…/user’;

@Component({
selector: ‘app-login’,
templateUrl: ‘./login.component.html’,
styleUrls: [‘./login.component.css’]
})
export class LoginComponent implements OnInit {

constructor(private authService: AuthService, private router: Router) { }

ngOnInit() {
}

login(form){
console.log(form.value);
this.authService.signIn(form.value).subscribe((res)=>{
console.log(“Logged in!”);
this.router.navigateByUrl(‘home’);
});
}

}

Again, we import and inject AuthService and Router via the component’s constructor then in the login() method we call the signIn() method of AuthService to authenticate the user.

In both the login() and register() methods we subscribe to the returned Observable and we use the Router navigateByUrl() method to navigate to a home page so you should also create a home page and map it to the home route.

Please note that we don’t do any error checking here. Subscribing to the Observable doesn’t guarantee that we get a successful response all the time so you should also do some basic error checking before navigating to the home page.


Originally published at  techiediaries.com on 10 Sep 2019



#angular #node-js

What is GEEK

Buddha Community

Send POST request to Node / Express.js server with Angular8

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

Deploy a Node.js App to Heroku's Free Tier + Keeping the App Alive | Node.js + Express.js

In this video, we’ll be going over how to quickly deploy your Node.js app to Heroku for FREE and how we can keep this app alive/online despite Heroku’s free tier’s limitations.

Building the Mars Rover Pictures of the Day App: https://www.youtube.com/watch?v=s5sygFQ_vLE

Kaffeine: https://kaffeine.herokuapp.com/
Other alternatives to keep Heroku apps alive:

Sections:
0:00 - Intro
0:22 - Discussing how to keep Heroku’s free apps alive
1:20 - Linking your Heroku app to your GitHub repo
2:47 - Setting up the server and GET endpoint to ping
7:09 - Setting up the config to start the app
8:46 - Verifying the deployment
9:36 - Keeping the app alive/online
10:23 - Conclusion

Found this video helpful? Feel free to support this channel here: https://ko-fi.com/jacksonyuan

#express.js #express #node.js #node #heroku's

sophia tondon

sophia tondon

1625114985

Top 10 NodeJs app Development Companies- ValueCoders

Node.js is a prominent tech trend in the space of web and mobile application development. It has been proven very efficient and useful for a variety of application development. Thus, all business owners are eager to leverage this technology for creating their applications.

Are you striving to develop an application using Node.js? But can’t decide which company to hire for NodeJS app development? Well! Don’t stress over it, as the following list of NodeJS app development companies is going to help you find the best partner.

Let’s take a glance at top NodeJS application development companies to hire developers in 2021 for developing a mind-blowing application solution.

Before enlisting companies, I would like to say that every company has a foundation on which they thrive. Their end goals, qualities, and excellence define their competence. Thus, I prepared this list by considering a number of aspects. While making this list, I have considered the following aspects:

  • Review and rating
  • Enlisted by software peer & forums
  • Hourly price
  • Offered services
  • Year of experience (Average 8+ years)
  • Credibility & Excellence
  • Served clients and more

I believe this list will help you out in choosing the best NodeJS service provider company. So, now let’s explore the top NodeJS developer companies to choose from in 2021.

#1. JSGuru

JSGuru is a top-rated NodeJS app development company with an innovative team of dedicated NodeJS developers engaged in catering best-class UI/UX design, software products, and AWS professional services.

It is a team of one of the most talented developers to hire for all types of innovative solution development, including social media, dating, enterprise, and business-oriented solutions. The company has worked for years with a number of startups and launched a variety of products by collaborating with big-name corporations like T-systems.

If you want to hire NodeJS developers to secure an outstanding application, I would definitely suggest them. They serve in the area of eLearning, FinTech, eCommerce, Telecommunications, Mobile Device Management, and more.

  • Ratings: 4.9/5.0

  • Founded: 2006

  • Headquarters: Banja Luka, Bosnia, and Herzegovina

  • Price: Starting from $50/hour

Visit Website - https://www.valuecoders.com/blog/technology-and-apps/top-node-js-app-development-companies

#node js developer #hire node js developer #hiring node js developers #node js development company #node.js development company #node js development services