項目準備
啟動服務
// server.js// 引入 expressconst express = require('express')// 創建服務器應用程序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
命令啟動服務
注:nodemon 命令需要全局安裝 nodemon( npm install --global nodemon
), 在瀏覽器訪問/user時如下,則說明開啟成功
實現簡單的 GET 請求接口
創建處理 get 請求的接口
app.get('/api/get', async (req, res) => { res.send('hello node.js')})
在vscode商店中下載 REST Client
新建一個 test.http 文件測試接口,點擊 Send Request
發送請求
// test.http@url=http://localhost:3001/api### get {{url}}/user
如上圖,get 請求成功
操作 MongoDB 數據庫
連接數據庫
建立數據庫模型
// 引入 mongoose const mongoose = require('mongoose')// 連接數據庫,自動新建 ExpressAuth 庫mongoose.connect('mongodb://localhost:27017/ExpressAuth', { useNewUrlParser: true, useCreateIndex: true})// 建立用戶表const UserSchema = new mongoose.Schema({ username: { type: String, unique: true }, password: { type: String, }})// 建立用戶數據庫模型const User = mongoose.model('User', userSchema)module.exports = { User }
簡單的 POST 請求
創建處理 POST 請求的接口
// server.jsapp.post('/api/register', async (req, res) => { console.log(req.body); res.send('ok')})app.use(express.json()) // 設置后可以用 req.body 獲取 POST 傳入 data
設置 /api/register
###POST {{url}}/registerContent-Type: application/json{ "username": "user1", "password": "123456"}
注冊用戶
// server.jsapp.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)})
數據庫里多了一條用戶數據:
密碼 bcrypt 加密
用戶登錄密碼解密
在 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,自定義密鑰
// 引入 jwtconst jwt = require('jsonwebtoken')// 解析 token 用的密鑰const SECRET = 'token_secret'
在登錄成功時創建 token
/* 生成 tokenjwt.sign() 接受兩個參數,一個是傳入的對象,一個是自定義的密鑰*/const token = jwt.sign({ id: String(user._id) }, SECRET)res.send({ user, token})
這樣我們在發送請求時,就能看到創建的 token
解密 token獲取登錄用戶
先在 server.js 處理 token
app.get('/api/profile', async (req, res) => { const raw = String(req.headers.authorization.split(' ').pop()) // 解密 token 獲取對應的 id const { id } = jwt.verify(raw, SECRET) req.user = await User.findById(id) res.send(req.user) })
發送請求,這里的請求頭是復制之前測試用的 token
### 個人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjZDI5YjFlMTIwOGEzNDBjODRhNDcwMCIsImlhdCI6MTU1NzM2ODM5M30.hCavY5T6MEvMx9jNebInPAeCT5ge1qkxPEI6ETdKR2U
服務端返回如下圖,則說明解析成功
配套完整代碼和注釋見 Github
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答