零售店铺项目:如何用Node.js连接Angular2/5与MySQL及实现登录页
Hey there! Let's walk through exactly how to connect your Angular 2/5 retail store app to a MySQL database using Node.js, plus build the login page you need first and add CRUD operation examples. Here's a step-by-step breakdown:
Angular (front-end) can't directly connect to MySQL—we need a Node.js backend to act as a middleman. The flow will be:
- Angular sends HTTP requests (like login, create, update) to Node.js APIs
- Node.js handles the request, talks to MySQL, and sends back a response
- Angular displays the result to the user
First, let's build the backend that connects to your MySQL database and exposes APIs.
2.1 Initialize Node.js Project & Install Dependencies
Create a new folder for your backend, then run:
npm init -y npm install express mysql2 cors body-parser
express: Builds the API servermysql2: MySQL driver for Node.js (better performance than the oldermysqlpackage)cors: Allows cross-origin requests (since Angular runs on a different port than Node.js)body-parser: Parses incoming request bodies
2.2 Create MySQL Connection File
Make a db.js file to handle the database connection:
const mysql = require('mysql2'); // Replace with your MySQL credentials const db = mysql.createConnection({ host: 'localhost', user: 'your_mysql_username', password: 'your_mysql_password', database: 'retail_store_db' // Your retail store database name }); db.connect((err) => { if (err) { console.error('Error connecting to MySQL:', err); return; } console.log('Connected to MySQL database successfully!'); }); module.exports = db;
2.3 Build the Login API
Create a server.js file to set up the Express server and login route:
const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const db = require('./db'); const app = express(); const port = 3000; app.use(cors()); app.use(bodyParser.json()); // Login API endpoint app.post('/api/login', (req, res) => { const { username, password } = req.body; // Query to check user credentials (replace with your users table schema) const query = 'SELECT * FROM users WHERE username = ? AND password = ?'; db.query(query, [username, password], (err, results) => { if (err) { return res.status(500).json({ message: 'Server error', error: err }); } if (results.length === 0) { return res.status(401).json({ message: 'Invalid username or password' }); } // If login is successful, send back user data (you can add JWT tokens here for security) res.status(200).json({ message: 'Login successful', user: results[0] }); }); }); app.listen(port, () => { console.log(`Node.js server running on port ${port}`); });
Note: For production, never store plain text passwords! Use a hashing library like
bcryptto hash passwords before storing them in MySQL.
Now let's create the login component in your Angular app.
3.1 Generate Login Component
Run this command in your Angular project folder:
ng generate component login
3.2 Update Login Component HTML (login.component.html)
<div class="login-container"> <h2>Retail Store Login</h2> <form (ngSubmit)="onLogin()" #loginForm="ngForm"> <div> <label>Username:</label> <input type="text" name="username" [(ngModel)]="username" required> </div> <div> <label>Password:</label> <input type="password" name="password" [(ngModel)]="password" required> </div> <button type="submit" [disabled]="!loginForm.valid">Login</button> <p *ngIf="errorMessage" class="error">{{ errorMessage }}</p> </form> </div>
3.3 Create Auth Service (auth.service.ts)
Generate a service to handle API calls:
ng generate service auth
Then update the service:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthService { private apiUrl = 'http://localhost:3000/api'; constructor(private http: HttpClient) { } login(username: string, password: string): Observable<any> { return this.http.post(`${this.apiUrl}/login`, { username, password }); } }
Don't forget to import HttpClientModule in your app.module.ts!
3.4 Update Login Component TS (login.component.ts)
import { Component } from '@angular/core'; import { AuthService } from '../auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent { username: string = ''; password: string = ''; errorMessage: string = ''; constructor(private authService: AuthService) { } onLogin() { this.authService.login(this.username, this.password).subscribe( (response) => { console.log('Login success:', response); // Store user info in localStorage or sessionStorage localStorage.setItem('currentUser', JSON.stringify(response.user)); // Redirect to dashboard or home page window.location.href = '/dashboard'; }, (error) => { this.errorMessage = error.error.message; } ); } }
Now let's add examples for Create, Read, Update, Delete operations using the same Node.js + Angular setup.
4.1 Node.js CRUD APIs (Add to server.js)
// Get all products (Read) app.get('/api/products', (req, res) => { const query = 'SELECT * FROM products'; db.query(query, (err, results) => { if (err) return res.status(500).json({ error: err }); res.status(200).json(results); }); }); // Add a new product (Create) app.post('/api/products', (req, res) => { const { name, price, stock } = req.body; const query = 'INSERT INTO products (name, price, stock) VALUES (?, ?, ?)'; db.query(query, [name, price, stock], (err, results) => { if (err) return res.status(500).json({ error: err }); res.status(201).json({ message: 'Product added successfully', id: results.insertId }); }); }); // Update a product (Update) app.put('/api/products/:id', (req, res) => { const { id } = req.params; const { name, price, stock } = req.body; const query = 'UPDATE products SET name = ?, price = ?, stock = ? WHERE id = ?'; db.query(query, [name, price, stock, id], (err, results) => { if (err) return res.status(500).json({ error: err }); if (results.affectedRows === 0) return res.status(404).json({ message: 'Product not found' }); res.status(200).json({ message: 'Product updated successfully' }); }); }); // Delete a product (Delete) app.delete('/api/products/:id', (req, res) => { const { id } = req.params; const query = 'DELETE FROM products WHERE id = ?'; db.query(query, [id], (err, results) => { if (err) return res.status(500).json({ error: err }); if (results.affectedRows === 0) return res.status(404).json({ message: 'Product not found' }); res.status(200).json({ message: 'Product deleted successfully' }); }); });
4.2 Angular Product Service (product.service.ts)
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ProductService { private apiUrl = 'http://localhost:3000/api/products'; constructor(private http: HttpClient) { } getProducts(): Observable<any[]> { return this.http.get<any[]>(this.apiUrl); } addProduct(product: any): Observable<any> { return this.http.post<any>(this.apiUrl, product); } updateProduct(id: number, product: any): Observable<any> { return this.http.put<any>(`${this.apiUrl}/${id}`, product); } deleteProduct(id: number): Observable<any> { return this.http.delete<any>(`${this.apiUrl}/${id}`); } }
- Make sure your MySQL server is running, and you've created the
usersandproductstables with the correct schema. - For security, add JWT authentication to protect your CRUD APIs (only logged-in users should access them).
- Test your APIs first with tools like Postman before connecting them to Angular.
内容的提问来源于stack exchange,提问作者Haja

