一、前言
通過本篇文章,你可掌握node.js關(guān)于注冊用戶、登錄以及驗(yàn)證等相關(guān)知識(shí)該用戶不存在英文,本篇中的代碼塊都處于一個(gè)文件index.js中。
二、相關(guān)技術(shù)點(diǎn)主要工具node相關(guān)包三、文件準(zhǔn)備創(chuàng)建 index.js文件進(jìn)行一些簡單的配置
// 引入 mysql 連接數(shù)據(jù)庫
const mysql = require("mysql");
// 數(shù)據(jù)庫配置
// 我是利用 sqlyog 可視化工具建立的數(shù)據(jù)庫 并且建立相應(yīng)的表 user
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
port: 3306,
database: "blog",
});
// 定義一個(gè)執(zhí)行 sql 語句的函數(shù) 并且返回一個(gè) promise 對象
const exec = (sql) => {
const promise = new Promise((resolve, reject) => {
con.query(sql, (err, result) => {

resolve(result);
});
});
return promise;
};
// 連接數(shù)據(jù)庫
con.connect();
// 引入其他相關(guān)包
const express = require("express");
var bodyParser = require("body-parser");
var bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
// 解析 post 請求體
app.use(bodyParser.json({ limit: "1mb" })); //body-parser 解析json格式數(shù)據(jù)
app.use(

bodyParser.urlencoded({
//此項(xiàng)必須在 bodyParser.json 下面,為參數(shù)編碼
extended: true,
})
);
// 此變量為解析 token 密匙 變量比較隱私 應(yīng)該放在其他地方 本文章簡單使用一下
// 值為開發(fā)者隨意設(shè)定的
const SECRET = "asdfjoijisadfjlkj";
// 創(chuàng)建服務(wù)器
const app = express();
// 監(jiān)聽3001端口
app.listen(3001, () => {
console.log("服務(wù)器啟動(dòng)");
});
四、接口編寫用戶注冊
app.post("/register", (req, res) => {

const username = req.body.username;
// 密碼進(jìn)行加密
const password = bcrypt.hashSync(req.body.password, 10);
const sql = `insert into user (username, password) values ('${username}', '${password}')`;
exec(sql).then((result) => {
return;
});
res.send("用戶注冊成功");
});
用戶登錄
app.post("/login", (req, res) => {
// 從請求中獲取請求體
const { username, password } = req.body;
const sql = `select * from user where username='${username}'`;
exec(sql).then((result) => {
const user = result[0];

// 如果查詢不到用戶
if (!user) {
res.send("用戶名不存在");
return;
}
// 判斷用戶輸入的密碼和數(shù)據(jù)庫存儲(chǔ)的是否對應(yīng) 返回 true 或者 false
const isPasswordValid = bcrypt.compareSync(password, user.password);
if (!isPasswordValid) {
res.send("密碼錯(cuò)誤");
return;
}
// 生成 token 將用戶的唯一標(biāo)識(shí) id 作為第一個(gè)參數(shù)
// SECRET 作為取得用戶 id 密匙
const token = jwt.sign({ id: user.id }, SECRET);
// 如果都通過了 則返回user 和 token
// 返回的 token 應(yīng)該存儲(chǔ)在客戶端 以便后續(xù)發(fā)起請求需要在請求頭里設(shè)置

res.send({ user, token });
});
});
用戶登錄后,才能訪問的接口
app.get("/profile", (req, res) => {
// 從請求頭里取出 token
const token = req.headers.authorization.split(" ")[1];
// token 驗(yàn)證取得 用戶 id
const { id } = jwt.verify(token, SECRET);
// 查詢用戶
const sql = `select * from user where id='${id}'`;
exec(sql).then((result) => {
// 返回用戶信息
res.send(result[0]);
});
});
五、總結(jié)
用戶注冊發(fā)起請求,后端將密碼加密后存儲(chǔ)到數(shù)據(jù)庫表中。登錄的時(shí)候該用戶不存在英文,先根據(jù) 查詢數(shù)據(jù)庫判斷是否有該用戶,沒有則返回用戶不存在,用戶存在則將登錄所傳的密碼與數(shù)據(jù)庫的密碼做對比,會(huì)返回 true 或者 false,若為 false,則返回密碼錯(cuò)誤,若為 true,則返回用戶信息和 token 值。訪問需要 token 驗(yàn)證的接口時(shí),在請求頭中拿到 token 并且根據(jù) token 查詢數(shù)據(jù)庫得到該用戶信息存在后,在進(jìn)行接下來的操作。