快速搭建Node.js(Express)用戶注冊(cè)、登錄以及授權(quán)的方法
項(xiàng)目準(zhǔn)備
- 建立一個(gè)文件夾,這里叫 EXPRESS-AUTH
- npm init -y
啟動(dòng)服務(wù)
- 新建一個(gè)server.js 或者 app.js
- npm i express
- 開啟端口,啟動(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)簡單的 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 文件測試接口,點(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ù)庫
- 安裝 mongodb 數(shù)據(jù)庫
- 在需要啟動(dòng)的盤符根目錄下新建 data/db 文件夾
- 在命令行對(duì)應(yīng)的盤符下輸入 mongod 命令,即可開啟服務(wù)
- 有需要可以下載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 }
簡單的 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í)長越長

用戶登錄密碼解密
在 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ù)制之前測試用的 token
### 個(gè)人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjZDI5YjFlMTIwOGEzNDBjODRhNDcwMCIsImlhdCI6MTU1NzM2ODM5M30.hCavY5T6MEvMx9jNebInPAeCT5ge1qkxPEI6ETdKR2U
服務(wù)端返回如下圖,則說明解析成功

配套完整代碼和注釋見 Github
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
從零學(xué)習(xí)node.js之mysql數(shù)據(jù)庫的操作(五)
因?yàn)榻佑|Node.JS已經(jīng)有一段時(shí)間了,最近粗略的研究了一下node.js操作數(shù)據(jù)庫的包,覺得node.js連接數(shù)據(jù)庫不錯(cuò)。下面這篇文章主要給大家介紹了node.js之mysql數(shù)據(jù)庫操作的相關(guān)資料,需要的朋友可以參考下。2017-02-02
NodeJS如何優(yōu)雅的實(shí)現(xiàn)Sleep休眠
這篇文章主要介紹了NodeJS如何優(yōu)雅的實(shí)現(xiàn)Sleep休眠問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09
Nodejs使用dgram模塊創(chuàng)建UDP服務(wù)詳解
這篇文章主要為大家介紹了Nodejs使用dgram模塊創(chuàng)建UDP服務(wù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
node.js學(xué)習(xí)筆記之koa框架和簡單爬蟲練習(xí)
這篇文章主要介紹了node.js學(xué)習(xí)筆記之koa框架和簡單爬蟲練習(xí),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12

