📅  最后修改于: 2023-12-03 15:17:36.196000             🧑  作者: Mango
Are you looking for a full-stack solution for your authentication needs? Look no further than the MEAN stack!
The MEAN stack is a combination of technologies that allow for the development of full-stack web applications. MEAN stands for:
By using the MEAN stack, you can create a complete web application that includes a database, server-side logic, and a modern front-end.
The MEAN stack is an ideal choice for building authentication systems for several reasons:
Implementing authentication with the MEAN stack involves several components. Here is a high-level overview of the process:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
});
module.exports = mongoose.model('User', UserSchema);
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const User = require('userModel');
mongoose.connect('mongodb://localhost/auth_demo', { useNewUrlParser: true });
const app = express();
app.use(bodyParser.json());
app.post('/register', (req, res) => {
const { name, email, password } = req.body;
const user = new User({ name, email, password });
user.save((err) => {
if (err) {
res.status(500).send('Error saving user to database');
} else {
res.status(200).send('User successfully registered');
}
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
<form (ngSubmit)="onSubmit()">
<label>
Email:
<input type="email" [(ngModel)]="email" name="email" required>
</label>
<br>
<label>
Password:
<input type="password" [(ngModel)]="password" name="password" required>
</label>
<br>
<button type="submit">Login</button>
</form>
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-login',
template: `
<form (ngSubmit)="onSubmit()">
<label>
Email:
<input type="email" [(ngModel)]="email" name="email" required>
</label>
<br>
<label>
Password:
<input type="password" [(ngModel)]="password" name="password" required>
</label>
<br>
<button type="submit">Login</button>
</form>
`,
})
export class LoginComponent {
email = '';
password = '';
constructor(private http: HttpClient) {}
onSubmit() {
this.http.post('/login', { email: this.email, password: this.password })
.subscribe((res) => {
console.log(`Response from server: ${res}`);
});
}
}
const jwt = require('jsonwebtoken');
// ...
app.post('/login', (req, res) => {
const { email, password } = req.body;
User.findOne({ email }, (err, user) => {
if (err || !user) {
res.status(401).send('User not found');
} else if (user.password !== password) {
res.status(401).send('Incorrect password');
} else {
const token = jwt.sign({ userId: user._id }, 'secret_key');
res.status(200).send({ token });
}
});
});
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
// Get the JWT from localStorage
const token = localStorage.getItem('token');
// Clone the request and attach the token
const authReq = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next.handle(authReq);
}
}
That's it! With these components in place, you can create a robust authentication system using the MEAN stack.
The MEAN stack is a powerful and flexible solution for building full-stack web applications. By leveraging technologies like MongoDB, Express, Angular, and Node.js, you can create feature-rich and scalable authentication systems that can meet the needs of any application.
If you're new to the MEAN stack, check out these resources to get started: