In the first part of this tutorial series, you learned how to get started creating an Angular web application. You learned how to set up the application and create the login component.
In this part of the series, you will further write about the REST API required to interact with the banking side of MongoDB. You will also create theHome
component, which will be displayed after the user successfully logs in.
start using
Let's start by cloning the source code for the first part of this tutorial series.
git clone https://github.com/royagasthyan/AngularBlogApp-Login AngularBlogApp-Home
Navigate to the project directory and install the required dependencies.
cd AngularBlogApp-Home/client npm install
After installing the dependencies, restart the application server.
npm start
Point your browser to http://localhost:4200 and the application should be running.
Create Login REST API
In the project folderAngularBlogApp-Home
, create another folder namedserver
. You'll write a REST API using Node.js.
Navigate to theserver
folder and initialize the project.
cd server npm init
Enter the required details and you should have your project initialized.
You will use theExpress
framework to create the server. InstallExpress
using the following command:
npm install express --save
After installingExpress
, create a file namedapp.js
. This will be the root file of the Node.js server.
Here is what theapp.js
file looks like:
const express = require('express') const app = express() app.get('/api/user/login', (req, res) => { res.send('Hello World!') }) app.listen(3000, () => console.log('blog server running on port 3000!'))
As shown in the code above, you importexpress
intoapp.js
. Usingexpress
, you create an applicationapp
.
Withapp
, you expose an endpoint/api/user/login
which will display a message. Start the Node.js server using the following command:
node app.js
Point your browser to http://localhost:3000/api/user/login and you should see the message.
You will make aPOST
request from the Angular service to the server using theUsername
andPassword
parameters. So the request parameters need to be parsed.
Installationbody-parser
, this is Node.js body parsing middleware, used to parse request parameters.
npm install body-parser --save
After the installation is complete, import it intoapp.js
.
const bodyParser = require('body-parser')
Add the following code to theapp.js
file.
app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended : false}))
The twobody-parser
options above return middleware that only parsesjson
andurlencoded
bodies, and only looks atContent-Type
Headers matching requesttype
options.
You will useMongoose
to interact withMongoDB
in Node.js. Therefore, installMongoose
using Node Package Manager (npm).
npm install mongoose --save
After installing mongoose, import it intoapp.js
.
const mongoose = require('mongoose');
Define the MongoDB database URL inapp.js
.
const url = 'mongodb://localhost/blogDb';
Let’s connect to the MongoDB database usingMongoose
. Its appearance is as follows:
app.post('/api/user/login', (req, res) => { mongoose.connect(url, function(err){ if(err) throw err; console.log('connected successfully, username is ',req.body.username,' password is ',req.body.password); }); })
If a connection is established, the message will be logged along with theusername
andpassword
.
Here is what theapp.js
file looks like:
const express = require('express') const bodyParser = require('body-parser') const app = express() const mongoose = require('mongoose'); const url = 'mongodb://localhost/blogDb'; app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended : false})) app.post('/api/user/login', (req, res) => { mongoose.connect(url, function(err){ if(err) throw err; console.log('connected successfully, username is ',req.body.username,' password is ',req.body.password); }); }) app.listen(3000, () => console.log('blog server running on port 3000!'))
Restart the node server using the following command:
node app.js
To connect to a Node server from an Angular application, you need to set up a proxy. Create a file namedproxy.json
in theclient/src
folder. Its appearance is as follows:
{ "/api/*": { "target": "http://localhost:3000", "secure": "false" } }
Modify the clientpackage.json
file to use the proxy file to launch the application.
"start": "ng serve --proxy-config proxy.json"
Save changes and start the client server.
npm start
Point your browser to http://localhost:4200 and enter your username and password. Click the login button and you should log the parameters into the node console.
Verify user login
To use Mongoose to interact with MongoDB, you need to define the schema and create a model. Within theserver
folder, create a folder namedmodel
.
Create a file nameduser.js
in themodel
folder. Add the following code to theuser.js
file:
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // create a schema const userSchema = new Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true }, name: { type: String } }, { collection : 'user' }); const User = mongoose.model('User', userSchema); module.exports = User;
As shown in the code above, you import mongoose intouser.js
. You created theuserSchema
using mongooseschema
and theUser
model using themongoose
model.
将user.js
文件导入到app.js
文件中。
const User = require('./model/user');
在查询 MongoDBuser
集合之前,您需要创建该集合。输入mongo
转到 MongoDB shell。使用以下命令创建集合user
:
db.createCollection('user')
插入您要查询的记录。
db.user.insert({ name: 'roy agasthyan', username: 'roy', password: '123' })
现在,一旦 mongoose 连接到 MongoDB,您将使用传入的用户名
和密码
从数据库中找到记录。API 如下所示:
app.post('/api/user/login', (req, res) => { mongoose.connect(url,{ useMongoClient: true }, function(err){ if(err) throw err; User.find({ username : req.body.username, password : req.body.password }, function(err, user){ if(err) throw err; if(user.length === 1){ return res.status(200).json({ status: 'success', data: user }) } else { return res.status(200).json({ status: 'fail', message: 'Login Failed' }) } }) }); })
如上面的代码所示,一旦收到数据库的响应,就会将其返回给客户端。
保存以上更改并尝试运行客户端和服务器。输入用户名roy
和密码123
,您应该能够在浏览器控制台中查看结果。
重定向到主页组件
用户验证成功后,您需要将用户重定向到Home
组件。因此,让我们首先创建Home
组件。
在src/app
文件夹中创建一个名为Home
的文件夹。创建一个名为home.component.html
的文件并添加以下 HTML 代码:
Lorem ipsum
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Read More ...
Subheading
Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.
Subheading
Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.
Subheading
Maecenas sed diam eget risus varius blandit sit amet non magna.
Subheading
Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.
Subheading
Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.
Subheading
Maecenas sed diam eget risus varius blandit sit amet non magna.
创建一个名为home.component.css
的文件并添加以下 CSS 样式:
.header, .marketing, .footer { padding-right: 1rem; padding-left: 1rem; } /* Custom page header */ .header { padding-bottom: 1rem; border-bottom: .05rem solid #e5e5e5; } .header h3 { margin-top: 0; margin-bottom: 0; line-height: 3rem; } /* Custom page footer */ .footer { padding-top: 1.5rem; color: #777; border-top: .05rem solid #e5e5e5; } /* Customize container */ @media (min-width: 48em) { .container { max-width: 46rem; } } .container-narrow > hr { margin: 2rem 0; } /* Main marketing message and sign up button */ .jumbotron { text-align: center; border-bottom: .05rem solid #e5e5e5; } .jumbotron .btn { padding: .75rem 1.5rem; font-size: 1.5rem; } /* Supporting marketing content */ .marketing { margin: 3rem 0; } .marketing p + h4 { margin-top: 1.5rem; } /* Responsive: Portrait tablets and up */ @media screen and (min-width: 48em) { /* Remove the padding we set earlier */ .header, .marketing, .footer { padding-right: 0; padding-left: 0; } /* Space out the masthead */ .header { margin-bottom: 2rem; } .jumbotron { border-bottom: 0; } }
创建名为home.component.ts
的组件文件并添加以下代码:
import { Component } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent { }
如上面的代码所示,您刚刚使用@Component
装饰器创建了HomeComponent
并指定了选择器
,templateUrl
和styleUrls
。
将HomeComponent
添加到NgModules
中的app.module.ts
。
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ROUTING } from './app.routing'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RootComponent } from './root/root.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; @NgModule({ declarations: [ RootComponent, LoginComponent, HomeComponent ], imports: [ BrowserModule, ROUTING, FormsModule, HttpClientModule ], providers: [], bootstrap: [RootComponent] }) export class AppModule { }
在app.routing.ts
中导入HomeComponent
,并为home
定义路由。
import { RouterModule, Routes } from '@angular/router'; import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; export const AppRoutes: Routes = [ { path: '', component: LoginComponent }, { path: 'home', component: HomeComponent } ]; export const ROUTING: ModuleWithProviders = RouterModule.forRoot(AppRoutes);
在login.component.ts
文件中的validateLogin
方法中,成功验证后会将用户重定向到HomeComponent
。要重定向,您需要导入 AngularRouter
。
import { Router } from '@angular/router';
如果 API 调用的响应成功,您将使用 AngularRouter
导航到HomeComponent
。
if(result['status'] === 'success') { this.router.navigate(['/home']); } else { alert('Wrong username password'); }
以下是login.component.ts
文件的外观:
import { Component } from '@angular/core'; import { LoginService } from './login.service'; import { User } from '../models/user.model'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], providers: [ LoginService ] }) export class LoginComponent { public user : User; constructor(private loginService: LoginService, private router: Router) { this.user = new User(); } validateLogin() { if(this.user.username && this.user.password) { this.loginService.validateLogin(this.user).subscribe(result => { console.log('result is ', result); if(result['status'] === 'success') { this.router.navigate(['/home']); } else { alert('Wrong username password'); } }, error => { console.log('error is ', error); }); } else { alert('enter user name and password'); } } }
保存以上更改并重新启动服务器。使用现有的用户名和密码登录应用程序,您将被重定向到HomeComponent
。
总结
在本教程中,您了解了如何编写用于用户登录的 REST API 端点。您学习了如何使用Mongoose
从 Node.js 与 MongoDB 进行交互。成功验证后,您了解了如何使用 AngularRouter
导航到HomeComponent
。
您学习编写 Angular 应用程序及其后端的体验如何?请在下面的评论中告诉我们您的想法和建议。
本教程的源代码可在 GitHub 上获取。
The above is the detailed content of Build a blog application homepage using Angular and MongoDB. For more information, please follow other related articles on the PHP Chinese website!