快速搭建Node.js(Express)用戶注冊、登錄以及授權(quán)的方法
項目準備
- 建立一個文件夾,這里叫 EXPRESS-AUTH
- npm init -y
啟動服務(wù)
- 新建一個server.js 或者 app.js
- npm i express
- 開啟端口,啟動服務(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') })
在命令行運行 nodemon .\server.js
命令啟動服務(wù)
注:nodemon 命令需要全局安裝 nodemon( npm install --global nodemon
), 在瀏覽器訪問/user時如下,則說明開啟成功
實現(xiàn)簡單的 GET 請求接口
創(chuàng)建處理 get 請求的接口
app.get('/api/get', async (req, res) => { res.send('hello node.js') })
在vscode商店中下載 REST Client
新建一個 test.http 文件測試接口,點擊 Send Request
發(fā)送請求
// test.http @url=http://localhost:3001/api ### get {{url}}/user
如上圖,get 請求成功
操作 MongoDB 數(shù)據(jù)庫
連接數(shù)據(jù)庫
- 安裝 mongodb 數(shù)據(jù)庫
- 在需要啟動的盤符根目錄下新建 data/db 文件夾
- 在命令行對應(yīng)的盤符下輸入 mongod 命令,即可開啟服務(wù)
- 有需要可以下載NoSQLBooster for MongoDB軟件
建立數(shù)據(jù)庫模型
- npm i mongoose
- 新建 model.js 操作數(shù)據(jù)庫
// 引入 mongoose const mongoose = require('mongoose') // 連接數(shù)據(jù)庫,自動新建 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 請求
創(chuàng)建處理 POST 請求的接口
// 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" }
注冊用戶
// 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方法接受兩個參數(shù),val 表示傳入的 password,10表示加密的等級,等級越高,所需轉(zhuǎn)化的時長越長
用戶登錄密碼解密
在 server.js 中添加處理 /login 的POST請求
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'
在登錄成功時創(chuàng)建 token
/* 生成 token jwt.sign() 接受兩個參數(shù),一個是傳入的對象,一個是自定義的密鑰 */ const token = jwt.sign({ id: String(user._id) }, SECRET) res.send({ user, token })
這樣我們在發(fā)送請求時,就能看到創(chuàng)建的 token
解密 token獲取登錄用戶
先在 server.js 處理 token
app.get('/api/profile', async (req, res) => { const raw = String(req.headers.authorization.split(' ').pop()) // 解密 token 獲取對應(yīng)的 id const { id } = jwt.verify(raw, SECRET) req.user = await User.findById(id) res.send(req.user) })
發(fā)送請求,這里的請求頭是復(fù)制之前測試用的 token
### 個人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjZDI5YjFlMTIwOGEzNDBjODRhNDcwMCIsImlhdCI6MTU1NzM2ODM5M30.hCavY5T6MEvMx9jNebInPAeCT5ge1qkxPEI6ETdKR2U
服務(wù)端返回如下圖,則說明解析成功
配套完整代碼和注釋見 Github
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js配合node-http-proxy解決本地開發(fā)ajax跨域問題
這篇文章主要介紹了Node.js配合node-http-proxy解決本地開發(fā)ajax跨域問題,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08我的Node.js學(xué)習(xí)之路(三)--node.js作用、回調(diào)、同步和異步代碼 以及事件循環(huán)
本篇文章主要介紹了node.js的幾個重要的知識點:node.js作用、回調(diào)、同步和異步代碼 以及事件循環(huán)2014-07-07Node.js實現(xiàn)爬取網(wǎng)站圖片的示例代碼
本文將利用Node.js開發(fā)一個小示例—爬取某圖片網(wǎng)站的圖片,文中涉及的知識點有https模塊、cheerio模塊、fs模塊和閉包,感興趣的可以了解一下2022-04-04