Table of Contents
start using
Create Login REST API
Verify user login
重定向到主页组件
总结
Home Web Front-end JS Tutorial Build a blog application homepage using Angular and MongoDB

Build a blog application homepage using Angular and MongoDB

Sep 03, 2023 pm 11:49 PM

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
Copy after login

Navigate to the project directory and install the required dependencies.

cd AngularBlogApp-Home/client
npm install
Copy after login

After installing the dependencies, restart the application server.

npm start
Copy after login
Copy after login

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
Copy after login

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
Copy after login

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!'))
Copy after login

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
Copy after login
Copy after login

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
Copy after login

After the installation is complete, import it into app.js .

const bodyParser = require('body-parser')
Copy after login

Add the following code to the app.js file.

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

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
Copy after login

After installing mongoose, import it into app.js.

const mongoose = require('mongoose');
Copy after login

Define the MongoDB database URL in app.js.

const url = 'mongodb://localhost/blogDb';
Copy after login

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);
	});
})
Copy after login

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!'))
Copy after login

Restart the node server using the following command:

node app.js
Copy after login
Copy after login

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"
	}
}
Copy after login

Modify the clientpackage.json file to use the proxy file to launch the application.

"start": "ng serve --proxy-config proxy.json"
Copy after login

Save changes and start the client server.

npm start
Copy after login
Copy after login

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;
Copy after login

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');
Copy after login

在查询 MongoDB user 集合之前,您需要创建该集合。输入 mongo 转到 MongoDB shell。使用以下命令创建集合 user

db.createCollection('user')
Copy after login

插入您要查询的记录。

 db.user.insert({
     name: 'roy agasthyan',
     username: 'roy',
     password: '123'
 })
Copy after login

现在,一旦 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'
				})
			}
			
		})
	});
})
Copy after login

如上面的代码所示,一旦收到数据库的响应,就会将其返回给客户端。

保存以上更改并尝试运行客户端和服务器。输入用户名 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 class="text-muted">Angular Blog App</h3>
</header>

<main role="main">

    <div class="jumbotron">
        <h1 class="display-3">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>Subheading</h4>
            <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p>

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

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

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

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

            <h4>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>
Copy after login

创建一个名为 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;
  }
}
Copy after login

创建名为 home.component.ts 的组件文件并添加以下代码:

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  
}
Copy after login

如上面的代码所示,您刚刚使用 @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 { }
Copy after login

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);
Copy after login

login.component.ts 文件中的 validateLogin 方法中,成功验证后会将用户重定向到 HomeComponent。要重定向,您需要导入 Angular Router

import { Router } from '@angular/router';
Copy after login

如果 API 调用的响应成功,您将使用 Angular Router 导航到 HomeComponent

if(result['status'] === 'success') {
  this.router.navigate(['/home']);
} else {
  alert('Wrong username password');
}
Copy after login

以下是 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');
  	}
  }

}
Copy after login

保存以上更改并重新启动服务器。使用现有的用户名和密码登录应用程序,您将被重定向到 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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles