亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

快速搭建Node.js(Express)用戶注冊(cè)、登錄以及授權(quán)的方法

 更新時(shí)間:2019年05月09日 14:37:18   作者:MrNow  
這篇文章主要介紹了快速搭建Node.js(Express)用戶注冊(cè)、登錄以及授權(quán),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

項(xiàng)目準(zhǔn)備

  1. 建立一個(gè)文件夾,這里叫 EXPRESS-AUTH
  2. npm init -y

啟動(dòng)服務(wù)

  1. 新建一個(gè)server.js 或者 app.js
  2. npm i express
  3. 開啟端口,啟動(dòng)服務(wù)
// server.js
// 引入 express
const express = require('express')
// 創(chuàng)建服務(wù)器應(yīng)用程序
const app = express()

app.get('/user', async (req, res) => {
 res.send('hello node.js')
})

app.listen(3001, () => {
 console.log('http://localhost:3001')
})

在命令行運(yùn)行 nodemon .\server.js 命令啟動(dòng)服務(wù)

注:nodemon 命令需要全局安裝 nodemon( npm install --global nodemon ), 在瀏覽器訪問/user時(shí)如下,則說明開啟成功

實(shí)現(xiàn)簡(jiǎn)單的 GET 請(qǐng)求接口

創(chuàng)建處理 get 請(qǐng)求的接口

app.get('/api/get', async (req, res) => {
 res.send('hello node.js')
})

在vscode商店中下載 REST Client

新建一個(gè) test.http 文件測(cè)試接口,點(diǎn)擊 Send Request 發(fā)送請(qǐng)求

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

### 
get {{url}}/user

如上圖,get 請(qǐng)求成功

操作 MongoDB 數(shù)據(jù)庫

連接數(shù)據(jù)庫

  1. 安裝 mongodb 數(shù)據(jù)庫
  2. 在需要啟動(dòng)的盤符根目錄下新建 data/db 文件夾
  3. 在命令行對(duì)應(yīng)的盤符下輸入 mongod 命令,即可開啟服務(wù)
  4. 有需要可以下載NoSQLBooster for MongoDB軟件

建立數(shù)據(jù)庫模型

  • npm i mongoose
  • 新建 model.js 操作數(shù)據(jù)庫
// 引入 mongoose 
const mongoose = require('mongoose')

// 連接數(shù)據(jù)庫,自動(dòng)新建 ExpressAuth 庫
mongoose.connect('mongodb://localhost:27017/ExpressAuth', {
 useNewUrlParser: true,
 useCreateIndex: true
})

// 建立用戶表
const UserSchema = new mongoose.Schema({
 username: {
 type: String,
 unique: true
 },
 password: {
 type: String,
 }
})

// 建立用戶數(shù)據(jù)庫模型
const User = mongoose.model('User', userSchema)

module.exports = { User }

簡(jiǎn)單的 POST 請(qǐng)求

創(chuàng)建處理 POST 請(qǐng)求的接口

// server.js
app.post('/api/register', async (req, res) => {
 console.log(req.body);
 res.send('ok')
})
app.use(express.json()) // 設(shè)置后可以用 req.body 獲取 POST 傳入 data

設(shè)置 /api/register

###
POST {{url}}/register
Content-Type: application/json

{
 "username": "user1",
 "password": "123456"
}

注冊(cè)用戶

// 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)
})

數(shù)據(jù)庫里多了一條用戶數(shù)據(jù):

密碼 bcrypt 加密

  • npm i bcrypt
  • 在 model.js 中設(shè)置密碼入庫前加密,這里的 hashSync方法接受兩個(gè)參數(shù),val 表示傳入的 password,10表示加密的等級(jí),等級(jí)越高,所需轉(zhuǎn)化的時(shí)長(zhǎng)越長(zhǎng)

用戶登錄密碼解密

在 server.js 中添加處理 /login 的POST請(qǐng)求

app.post('/api/login', async (req, res) => {
 const user = await User.findOne({
 username: req.body.username
 })
 if (!user) {
 return res.status(422).send({
  message: '用戶名不存在'
 })
 }
 // bcrypt.compareSync 解密匹配,返回 boolean 值
 const isPasswordValid = require('bcrypt').compareSync(
 req.body.password,
 user.password
 )
 if (!isPasswordValid) {
 return res.status(422).send({
  message: '密碼無效'
 })
 }
 res.send({
 user
 })
})

登錄添加 token

安裝 jsonwebtoken npm i jsonwebtoken
引入 jsonwebtoken,自定義密鑰

// 引入 jwt
const jwt = require('jsonwebtoken')
// 解析 token 用的密鑰
const SECRET = 'token_secret'

在登錄成功時(shí)創(chuàng)建 token

/* 
生成 token
jwt.sign() 接受兩個(gè)參數(shù),一個(gè)是傳入的對(duì)象,一個(gè)是自定義的密鑰
*/
const token = jwt.sign({ id: String(user._id) }, SECRET)
res.send({
 user,
 token
})

這樣我們?cè)诎l(fā)送請(qǐng)求時(shí),就能看到創(chuàng)建的 token

解密 token獲取登錄用戶

先在 server.js 處理 token

app.get('/api/profile', async (req, res) => {
 const raw = String(req.headers.authorization.split(' ').pop())
 // 解密 token 獲取對(duì)應(yīng)的 id
 const { id } = jwt.verify(raw, SECRET)
 req.user = await User.findById(id)
 res.send(req.user) 
})

發(fā)送請(qǐng)求,這里的請(qǐng)求頭是復(fù)制之前測(cè)試用的 token

### 個(gè)人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjZDI5YjFlMTIwOGEzNDBjODRhNDcwMCIsImlhdCI6MTU1NzM2ODM5M30.hCavY5T6MEvMx9jNebInPAeCT5ge1qkxPEI6ETdKR2U

服務(wù)端返回如下圖,則說明解析成功

配套完整代碼和注釋見 Github

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論