The simplest MEAN Stack Tutorial on Web you would found. MEAN stack is trending since 2015 and it is not slowing down anytime soon. MEAN stands for MongoDB, Express Js, Angular, and NodeJS. This tutorial is for developers who have not even worked with any of this one too. SO, relax this is not going to disappoint and leave you hanging in between. We promise. In this tutorial, we will build a NodeJs Express Server where we are using express routing, body-parser to handle requests from angular application, that establish a connection with MongoDB database. We will be building a separate application for Angular. SO, we have two applications here. Don’t worry, it is still simple. We will be doing basic get and post from application to the server and be interacting with the database. SO, not complicating with authentication and stuff. Keeping it simplest possible. So, let’s get coding now.
Setting Up NodeJS Express Server Application
Here we are building the simplest NodeJs Express Server Possible in this MEAN Stack tutorial. Routing would be via Express default routing. For parsing the requests we would be using body-parser for the incoming request. And establish connection with MongoDB using Mongoclient. The prerequisites remain that you have nodejs and npm installed in the system. Under A folder, use npm init to package.json and we are good to go. The server is being configured for port 3000 here and all the code is kept at app.js only. So, to run use node app.js command. And then on browser type localhost:3000
Install the following dependencies:
npm install express
npm install body-parser
npm install mongodb –save
Add the code in app.js
var express=require('express'); var app=express(); const bodyParser = require('body-parser'); const MongoClient = require('mongodb').MongoClient; const uri = "mongodb+srv://<username>:<Password>1@cluster0-xxxxx.mongodb.net/test"; const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology: true}); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.all("/*", function(req, res, next){ res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With'); next(); }); app.post('/insert',function(req,res) { client.connect(err => { const collection = client.db('EngineerDiariesDB').collection('Profile'); console.log("connected"); var object={id:3,username:req.body.username} collection.insertOne(object, function(err, res) { if (err) console.log(err) ; console.log("1 record inserted"); }); }); res.send(req.body) }); app.post('/select',function(req,res) { client.connect(err => { const collection = client.db('EngineerDiariesDB').collection('Profile'); console.log("connected"); collection.find({}).toArray(function(err, result) { if (err) console.log(err); console.log(result); res.send(result); }); }); }); var server=app.listen(3000,function() {});
Explanation:
uri contains the mongodb connection string . app.all() contains headers to enable cors as the request would be from the angular application server. There are two routes (/insert) that would insert the req.body into the MongoDB and /select to return the collection array of documents. EngineerdiariesDB is the database name here and Profile is the name of the collection. Again the nodejs server is hosted at port 3000. to ensure that you have established connection with DB we have logged Connected message in the console. Congratulations you have completed the first part of the Mean stack tutorial. Now, we will create an angular application that will send a request to this server.
Setting Up Angular Application
As discussed above we would be creating a separate application for angular. Under angular folder run ng new angularapp. This will take a few minutes to set up and say yes to the routing part. Move into the directory using cd .\angularapp\ . Next, we will create a signup component using ng g c signup and to run the angular server use command ng serve –o . So, you now have an angular application at port 4200 set up.
Add default route to signup component
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { SignupComponent } from './signup/signup.component'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot( [{path: '', component: SignupComponent}])], exports: [RouterModule] }) export class AppRoutingModule { }
Create a user model
create a class named user.ts where we need only 1 parameter username and add the following code to it.
export class user { username:string }
Add the following modules in app.module.ts
Here we have added FormsModule for two way binding and httpclient to establish connection with the server
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { SignupComponent } from './signup/signup.component'; import {HttpClientModule} from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, SignupComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Comment index.html
By default, they have added logo and text which we don’t require. So, better to comment that out.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angularapp</title> <base href="/"> </head> <body> <app-root></app-root> </body> </html>
Add following code to signup.html
Here we have created a basic form which binds usrname to the user1 object via two-way binding and on submit button calls formSubmit() and below list out the username and id when called on init() as in .ts code will look below.
<div> <div> <h1>Signup Form..</h1> </div> <div> <form > <label >Name:</label> <input name="username" id="username" [(ngModel)]="user1.username" #username="ngModel" type="text"/> <input type="button" value="Submit" (click)="formSubmit(user1.username)"/> </form> </div> <div> <h1>List of Username:</h1> <ul *ngFor="let item of data;index as i;"> <li></li> <li></li> </ul> </div> </div>
Add following code to signup.ts
Here we have declared user1 object. Onit() we call viewData() to get the objects via httprequest to select endpoint. and on formSubmit() we insert the data using /insert endpoint. Replace the ipaddress though and we have successfully completed step 2 of this mean stack tutorial.
import { Component, OnInit } from '@angular/core'; import { user } from '../user'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.css'] }) export class SignupComponent implements OnInit { user1:user; data:any; constructor(private http: HttpClient) { this.user1=new user(); } ngOnInit() { this.viewData(); } formSubmit( username:string) { console.log(username); debugger; const headers = new HttpHeaders() .set('Authorization', 'my-auth-token') .set('Content-Type', 'application/json'); this.http.post('http://ipaddress:3000/insert', JSON.stringify(this.user1), { headers: headers }) .subscribe(data => { console.log(data); }); } viewData() { const headers = new HttpHeaders() .set('Authorization', 'my-auth-token') .set('Content-Type', 'application/json'); this.http.post('http://ipaddress:3000/select',JSON.stringify(this.user1),{ headers: headers}) .subscribe(data => { console.log(data); this.data=data; }); } }
Setting up MongoDB for the Mean stack tutorial
Here we have created EngineerDiariesDB as database and Profile as the collection been used in the tutorial.
And we have successfully completed this mean stack tutorial. And you deserve a party because not a lot of people exactly know-how the full stack works also.
Similar Posts:
from Engineer Diaries https://ift.tt/2zeAsuM
0 Comments