search
HomeWeb Front-endJS TutorialBuild a blog application homepage using Angular and MongoDB

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 the Home 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 folder AngularBlogApp-Home, create another folder named server. You'll write a REST API using Node.js.

Navigate to the server folder and initialize the project.

cd server
npm init

Enter the required details and you should have your project initialized.

You will use the Express framework to create the server. Install Express using the following command:

npm install express --save

After installing Express, create a file named app.js. This will be the root file of the Node.js server.

Here is what the app.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 import express into app.js. Using express, you create an application app.

With app, 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 a POST request from the Angular service to the server using the Username and Password parameters. So the request parameters need to be parsed.

Installation body-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 into app.js .

const bodyParser = require('body-parser')

Add the following code to the app.js file.

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : false}))

The two body-parser options above return middleware that only parses json and urlencoded bodies, and only looks at Content-Type Headers matching request type options.

You will use Mongoose to interact with MongoDB in Node.js. Therefore, install Mongoose using Node Package Manager (npm).

npm install mongoose --save

After installing mongoose, import it into app.js.

const mongoose = require('mongoose');

Define the MongoDB database URL in app.js.

const url = 'mongodb://localhost/blogDb';

Let’s connect to the MongoDB database using Mongoose. 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 the username and password .

Here is what the app.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 named proxy.json in the client/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 the server folder, create a folder named model.

Create a file named user.js in the model folder. Add the following code to the user.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 into user.js. You created the userSchema using mongoose schema and the User model using the mongoose model.

user.js 文件导入到 app.js 文件中。

const User = require('./model/user');

在查询 MongoDB user 集合之前,您需要创建该集合。输入 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 代码:

<header class="header clearfix">
    <nav>
        <ul class="nav nav-pills float-right">
            <li class="nav-item">
                <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Add</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Logout</a>
            </li>
        </ul>
    </nav>
    <h3 id="Angular-Blog-App">Angular Blog App</h3>
</header>

<main role="main">

    <div class="jumbotron">
        <h1 id="Lorem-ipsum">Lorem ipsum</h1>
        <p class="lead">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.</p>
        <p><a class="btn btn-lg btn-success" href="#" role="button">Read More ...</a></p>
    </div>

    <div class="row marketing">
        <div class="col-lg-6">
            <h4 id="Subheading">Subheading</h4>
            <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p>

            <h4 id="Subheading">Subheading</h4>
            <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.</p>

            <h4 id="Subheading">Subheading</h4>
            <p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p>
        </div>

        <div class="col-lg-6">
            <h4 id="Subheading">Subheading</h4>
            <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p>

            <h4 id="Subheading">Subheading</h4>
            <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.</p>

            <h4 id="Subheading">Subheading</h4>
            <p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p>
        </div>
    </div>

</main>

<footer class="footer">
    <p>&copy; Company 2017</p>
</footer>

创建一个名为 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 并指定了 选择器 , templateUrlstyleUrls

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。要重定向,您需要导入 Angular Router

import { Router } from '@angular/router';

如果 API 调用的响应成功,您将使用 Angular Router 导航到 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

使用 Angular 和 MongoDB 构建博客应用程序主页

总结

在本教程中,您了解了如何编写用于用户登录的 REST API 端点。您学习了如何使用 Mongoose 从 Node.js 与 MongoDB 进行交互。成功验证后,您了解了如何使用 Angular Router 导航到 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.