Project preparation

  1. Create a folder called express-Auth
  2. npm init -y

Start the service

  1. Create a new server.js or app.js file
  2. npm i express
  3. 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

  1. Create an interface to handle GET requests
app.get('/api/get'.async (req, res) => {
  res.send('hello node.js')})Copy the code
  1. Download the REST Client from the vscode store

    To create a test. HTTP file test interface, clickSend RequestSend the request

// test.http
@url=http://localhost:3001/api

### 
get {{url}}/user
Copy the code

Operating the MongoDB database

  1. 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 wantNoSQLBooster for MongoDBsoftware
  1. 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

  1. 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
  1. Set/API/register
# # #
POST {{url}}/register
Content-Type: application/json

{
  "username": "user1"."password": "123456"
}
Copy the code
  1. 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

  1. npm i bcrypt
  2. 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

  1. 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

  1. Install jsonwebtokennpm i jsonwebtoken
  2. Jsonwebtoken is introduced to customize the key
// add JWT const JWT = require('jsonwebtoken'Const SECRET = const SECRET ='token_secret'
Copy the code
  1. 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

  1. 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
  1. 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