Project preparation
- Create a folder called express-Auth
- npm init -y
Start the service
- Create a new server.js or app.js file
npm i express
- Enable the port to enable the service
// server.js
/ / into the express
const express = require('express')
// Create server application
const app = express()
app.get('/user'.async (req, res) => {
res.send('hello node.js')
})
app.listen(3001, () = > {console.log('http://localhost:3001')})Copy the code
Run the nodemon.\ server.js command on the cli to start the service
Note: The nodemon command requires that the nodemon(NPM install –global nodemon) command be installed globally. If the browser accesses /user as follows, the command is successfully enabled
Implement a simple GET request interface
- Create an interface to handle GET requests
app.get('/api/get'.async (req, res) => {
res.send('hello node.js')})Copy the code
- Download the REST Client from the vscode store
To create a test. HTTP file test interface, click
Send Request
Send the request
// test.http
@url=http://localhost:3001/api
###
get {{url}}/user
Copy the code
Operating the MongoDB database
- Connecting to a Database
- Installing the mongodb Database
- Create a data/ DB folder in the root directory of the disk to be started
- To enable the service, enter the mongod command in the corresponding drive letter on the cli
- You can download it if you want
NoSQLBooster for MongoDB
software
- Build a database model
npm i mongoose
- Create a new model.js action database
// const mongoose = require('mongoose') Automatic new ExpressAuth library mongoose. Connect (' mongo: / / localhost: 27017 / ExpressAuth ', {useNewUrlParser: true, useCreateIndex: // Create user table const UserSchema = new mongoose.Schema({username: {type: String, unique: true}, password: {type: Const User = mongoose. Model ('User', userSchema) module.exports = {User}) // exports = {User}Copy the code
Simple POST request
- Create an interface to handle POST requests
// server.js
app.post('/api/register'.async (req, res) => {
console.log(req.body);
res.send('ok')
})
app.use(express.json()) // Req.body can be used to get the incoming POST data
Copy the code
- Set/API/register
# # #
POST {{url}}/register
Content-Type: application/json
{
"username": "user1"."password": "123456"
}
Copy the code
- Registered users
// server.js
app.post('/api/register'.async (req, res) => {
// console.log(req.body);
const user = await User.create({
username: req.body.username,
password: req.body.password
})
res.send(user)
})
Copy the code
A user’s data is added to the database:
Password bcrypt encryption
npm i bcrypt
- The hashSync method takes two parameters: val denotes the password passed in, and 10 denotes the level of encryption. The higher the level, the longer the conversion takes
Decrypt user login passwords
- Add a POST request to handle /login in server.js
app.post('/api/login', async (req, res) => {
const user = await User.findOne({
username: req.body.username
})
if(! user) {return res.status(422).send({
message: 'Username does not exist'})} // bcrypt.compareSync returns Boolean const isPasswordValid = require('bcrypt').compareSync(
req.body.password,
user.password
)
if(! isPasswordValid) {return res.status(422).send({
message: 'Password invalid'
})
}
res.send({
user
})
})
Copy the code
Login Adding a Token
- Install jsonwebtoken
npm i jsonwebtoken
- Jsonwebtoken is introduced to customize the key
// add JWT const JWT = require('jsonwebtoken'Const SECRET = const SECRET ='token_secret'
Copy the code
- The token is created upon a successful login
Jwt.sign () takes two arguments, one for the passed object and one for the custom key */
const token = jwt.sign({ id: String(user._id) }, SECRET)
res.send({
user,
token
})
Copy the code
This way we can see the token created when we send the request
Decrypt the token to obtain the login user
- Tokens are processed in server.js first
app.get('/api/profile'.async (req, res) => {
const raw = String(req.headers.authorization.split(' ').pop())
// Decrypt the token to obtain the corresponding ID
const { id } = jwt.verify(raw, SECRET)
req.user = await User.findById(id)
res.send(req.user)
})
Copy the code
- Send the request, where the request header is the token used to replicate the previous test
### Personal informationget {{url}}/profile Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjZDI5YjFlMTIwOGEzNDBjODRhNDcwMCIsImlhdCI6MTU1NzM2ODM5M30.hCavY5T6MEvMx9j NebInPAeCT5ge1qkxPEI6ETdKR2UCopy the code
If the following figure is displayed on the server, the resolution is successful
NodeJs(Express) user registration, login and authorization in 1 hour
See Github for complete code and comments