node.js+postman+mongodb搭建測(cè)試注冊(cè)接口的實(shí)現(xiàn)
準(zhǔn)備工作
申請(qǐng)一個(gè)免費(fèi)的MongoDB
到https://www.mlab.com
注冊(cè)申請(qǐng)一個(gè)500M的MongoDB數(shù)據(jù)庫。登錄后手動(dòng)在創(chuàng)建Databases下的Collections中手動(dòng)創(chuàng)建一個(gè)數(shù)據(jù)庫node_app。
在個(gè)人首頁點(diǎn)擊Connect獲取node.js連接MongoDB數(shù)據(jù)庫的字符串為
mongodb+srv://<username>:<password>@cluster0.ylpaf.mongodb.net/node_app
將其中<username>:<password>修改為自己設(shè)定的數(shù)據(jù)庫用戶名和密碼。
下載安裝Postman
到https://www.postman.com/
注冊(cè)一個(gè)賬號(hào),下載安裝Postman agent,即可方便地進(jìn)行GET/POST/PUT等測(cè)試。
mongodb連接串配置
安裝mongoose用于連接數(shù)據(jù)庫:
> npm install mongoose >? > cd C:\Users\xiaoming\source\repos\node_demo\node_app > mkdir config > cd config > new-item keys.js -type file
編輯keys.js配置連接串:
module.exports = { mongoURI: "mongodb+srv://<username>:<password>@cluster0.ylpaf.mongodb.net/node_app" }
編輯server.js入口文件:
const express = require("express"); const mongoose = require("mongoose"); const app = express(); const db = require("./config/keys").mongoURI; mongoose.connect(db) ? ? ? ? .then(() => console.log("MongoDB connected.")) ? ? ? ? .catch(err => console.log(err)); app.get("/", (req, res) => { ? ? res.send("Hello World!"); }) const port = process.env.PORT || 5000; app.listen(port, () => { ? ? console.log(`Server running on port ${port}`); })
檢查是否能連接到數(shù)據(jù)庫:
> nodemon server.js [nodemon] 2.0.16 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Server running on port 5000 MongoDB connected.
數(shù)據(jù)庫連接正常。
GET請(qǐng)求測(cè)試
創(chuàng)建路由文件
C:\Users\xiaoming\source\repos\node_demo\node_app\routes\api\users.js
編輯users.js并添加GET請(qǐng)求:
// login & registtration const express = require("express"); const router = express.Router(); router.get("/test", (req,res) => { ? ? res.json({msg:"Login succeeded!"}) }) module.exports = router;
編輯server.js,導(dǎo)入并使用users.js:
const express = require("express"); const mongoose = require("mongoose"); const app = express(); const users = require("./routes/api/users");? const db = require("./config/keys").mongoURI; mongoose.connect(db) ? ? .then(() => console.log("MongoDB connected.")) ? ? .catch(err => console.log(err)); // 設(shè)置app路由 app.get("/", (req, res) => { ? ? res.send("Hello World!"); }) // 使用users app.use("/api/users", users); const port = process.env.PORT || 5000; app.listen(port, () => { ? ? console.log(`Server running on port ${port}`); })
訪問
http://localhost:5000/api/users/test
可以看到
{"msg":"Login succeeded!"}
注冊(cè)接口搭建
創(chuàng)建User數(shù)據(jù)模型
創(chuàng)建用戶數(shù)據(jù)模型文件
C:\Users\xiaoming\source\repos\node_demo\node_app\models\User.js
編輯User.js創(chuàng)建用戶數(shù)據(jù)模型:
const mongoose = require("mongoose"); const Schema = mongoose.Schema; // create Schema const UserSchema = new Schema({ ? ? name:{ ? ? ? ? type: String, ? ? ? ? required: true ? ? }, ? ? email: { ? ? ? ? type: String, ? ? ? ? required: true ? ? }, ? ? password: { ? ? ? ? type: String, ? ? ? ? required: true ? ? }, ? ? avatar: { ? ? ? ? type: String ? ? }, ? ? date: { ? ? ? ? type: Date, ? ? ? ? default: Date.now ? ? }, }) module.exports = User = mongoose.model("users", UserSchema);
使用body-parser中間件
安裝body-parser中間件,可以方便地處理HTTP請(qǐng)求。
> npm install body-parser
編輯server.js使用body-parser:
const express = require("express"); const mongoose = require("mongoose"); const bodyParser = require("body-parser"); const app = express(); const users = require("./routes/api/users");? const db = require("./config/keys").mongoURI; app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); mongoose.connect(db) ? ? .then(() => console.log("MongoDB connected.")) ? ? .catch(err => console.log(err)); app.get("/", (req, res) => { ? ? res.send("Hello World!"); }) app.use("/api/users", users); const port = process.env.PORT || 5000; app.listen(port, () => { ? ? console.log(`Server running on port ${port}`); })
POST請(qǐng)求測(cè)試
編輯users.js增加POST請(qǐng)求:
// @login & registtration const express = require("express"); const router = express.Router(); /* ?* $route GET /api/users/test ?* @desc return requested json data ?* @access public ?*/ router.get("/test", (req,res) => { ? ? res.json({msg:"Login succeeded!"}) }) /* ?* $route POST /api/users/register ?* @desc return requested json data ?* @access public ?*/ router.post("/register", (req, res) => { ? ? console.log(req.body); }) module.exports = router;
POST中暫時(shí)只有一個(gè)打印請(qǐng)求體的操作。
在Postman中的Workspace中測(cè)試:
POST http://localhost:5000/api/users/register
Body選擇x-www-form-urlencoded,在KEY和VALUE中填入測(cè)試內(nèi)容:
KEY VALUE email harlie@google.com
查看終端輸出:
Server running on port 5000
MongoDB connected.
[Object: null prototype] { email: 'harlie@google.com' }
說明成功獲取到了req.body。
使用User數(shù)據(jù)模型
首先安裝bcrypt包。bcrypt可以用來加密注冊(cè)用戶的密碼,避免在數(shù)據(jù)庫中存儲(chǔ)明文密碼。在https://www.npmjs.com/上可以查看bcrypt包的用法介紹。
> npm install bcrypt
編輯users.js引入并使用User數(shù)據(jù)模型:
// @login & registtration const express = require("express"); const router = express.Router(); const bcrypt = require("bcrypt"); const User = require("../../models/User.js"); /* ?* $route GET /api/users/test ?* @desc return requested json data ?* @access public ?*/ router.get("/test", (req,res) => { ? ? res.json({msg:"Login succeeded!"}) }) /* ?* $route POST /api/users/register ?* @desc return requested json data ?* @access public ?*/ router.post("/register", (req, res) => { ? ? //console.log(req.body); ? ? // check if email already exists ? ? User.findOne({ email: req.body.email }) ? ? ? ? .then((user) => { ? ? ? ? ? ? if (user) { ? ? ? ? ? ? ? ? return res.status(400).json({ email: "郵箱已被注冊(cè)!" }) ? ? ? ? ? ? } else { ? ? ? ? ? ? ? ? const newUser = new User({ ? ? ? ? ? ? ? ? ? ? name: req.body.name, ? ? ? ? ? ? ? ? ? ? email: req.body.email, ? ? ? ? ? ? ? ? ? ? password: req.body.password ? ? ? ? ? ? ? ? }) ? ? ? ? ? ? ? ? // encrypt newUser password ? ? ? ? ? ? ? ? bcrypt.genSalt(10, function (err, salt) { ? ? ? ? ? ? ? ? ? ? bcrypt.hash(newUser.password, salt, (err, hash) => { ? ? ? ? ? ? ? ? ? ? ? ? if (err) throw err; ? ? ? ? ? ? ? ? ? ? ? ? newUser.password = hash; ? ? ? ? ? ? ? ? ? ? ? ? newUser.save() ? ? ? ? ? ? ? ? ? ? ? ? ? ? .then(user => res.json(user)) ? ? ? ? ? ? ? ? ? ? ? ? ? ? .catch(err => console.log(err)); ? ? ? ? ? ? ? ? ? ? }); ? ? ? ? ? ? ? ? }); ? ? ? ? ? ? } ? ? ? ? }) }) module.exports = router;
在Postman中的Workspace中測(cè)試POST http://localhost:5000/api/users/register。Body選擇x-www-form-urlencoded,在KEY和VALUE中填入測(cè)試內(nèi)容:
email godfrey@eldenring.com name godfrey password 123456
查看測(cè)試輸出
{ "name": "godfrey", "email": "godfrey@eldenring.com", "password": "$2b$10$hoGzFeIdZyCwEotsYhxEheoGNOCE4QnYYh/WkKoGkuPT0xZI9H10C", "_id": "62a4482c00990937d819ea6d", "date": "2022-06-11T07:45:48.437Z", "__v": 0 }
打開mongodb,在DATABASES下的node_app中查看,會(huì)發(fā)現(xiàn)多出了一個(gè)users的Collection,其中剛好存儲(chǔ)了上面我們剛通過POST請(qǐng)求插入的一條數(shù)據(jù)。
使用gravatar處理頭像
在https://www.npmjs.com/package/gravatar中查看gravatar的使用方法。
安裝gravatar
> npm i gravatar
編輯users.js增加注冊(cè)頭像(avatar)處理:
// @login & registtration const express = require("express"); const router = express.Router(); const bcrypt = require("bcrypt"); const gravatar = require("gravatar"); const User = require("../../models/User.js"); /* ?* $route GET /api/users/test ?* @desc return requested json data ?* @access public ?*/ router.get("/test", (req,res) => { ? ? res.json({msg:"Login succeeded!"}) }) /* ?* $route POST /api/users/register ?* @desc return requested json data ?* @access public ?*/ router.post("/register", (req, res) => { ? ? //console.log(req.body); ? ? // check if email already exists ? ? User.findOne({ email: req.body.email }) ? ? ? ? .then((user) => { ? ? ? ? ? ? if (user) { ? ? ? ? ? ? ? ? return res.status(400).json({ email: "Email already registered!" }) ? ? ? ? ? ? } else { ? ? ? ? ? ? ? ? const avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' }); ? ? ? ? ? ? ? ? const newUser = new User({ ? ? ? ? ? ? ? ? ? ? name: req.body.name, ? ? ? ? ? ? ? ? ? ? email: req.body.email, ? ? ? ? ? ? ? ? ? ? avatar, ? ? ? ? ? ? ? ? ? ? password: req.body.password ? ? ? ? ? ? ? ? }) ? ? ? ? ? ? ? ? // encrypt newUser password ? ? ? ? ? ? ? ? bcrypt.genSalt(10, function (err, salt) { ? ? ? ? ? ? ? ? ? ? bcrypt.hash(newUser.password, salt, (err, hash) => { ? ? ? ? ? ? ? ? ? ? ? ? if (err) throw err; ? ? ? ? ? ? ? ? ? ? ? ? newUser.password = hash; ? ? ? ? ? ? ? ? ? ? ? ? newUser.save() ? ? ? ? ? ? ? ? ? ? ? ? ? ? .then(user => res.json(user)) ? ? ? ? ? ? ? ? ? ? ? ? ? ? .catch(err => console.log(err)); ? ? ? ? ? ? ? ? ? ? }); ? ? ? ? ? ? ? ? }); ? ? ? ? ? ? } ? ? ? ? }) }) module.exports = router;
在Postman中的Workspace中測(cè)試POST http://localhost:5000/api/users/register,Body選擇x-www-form-urlencoded。
在KEY和VALUE中填入測(cè)試內(nèi)容:
email ? ? godfrey@eldenring.com name ? ? ?godfrey password ?123456
測(cè)試會(huì)返回報(bào)錯(cuò)
{ "email": "Email already registered!" }
在KEY和VALUE中填入測(cè)試內(nèi)容:
email mohg@eldenring.com name mohg password 123456
測(cè)試返回
{ "name": "mohg", "email": "mohg@eldenring.com", "password": "$2b$10$uSV2tmA5jH6veLTz1Lt5g.iD5QKtbJFXwGsJilDMxIqw7dZefpDz.", "avatar": "http://www.gravatar.com/avatar/c5515cb5392d5e8a91b6e34a11120ff1?s=200&r=pg&d=mm", "_id": "62a44f12d2c5293f0b8e9c2b", "date": "2022-06-11T08:15:14.410Z", "__v": 0 }
在瀏覽器中打開
www.gravatar.com/avatar/c5515cb5392d5e8a91b6e34a11120ff1?s=200&r=pg&d=mm
到此這篇關(guān)于node.js+postman+mongodb搭建測(cè)試注冊(cè)接口的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)node postman mongodb注冊(cè)接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js命令行/批處理中如何更改Linux用戶密碼淺析
這篇文章主要給大家介紹了關(guān)于Node.js命令行/批處理中如何更改Linux用戶密碼的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07express框架實(shí)現(xiàn)基于Websocket建立的簡(jiǎn)易聊天室
本篇文章主要介紹了express框架實(shí)現(xiàn)基于Websocket建立的簡(jiǎn)易聊天室,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08Node綁定全局TraceID的實(shí)現(xiàn)方法
這篇文章主要介紹了Node 綁定全局 TraceID的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11node基于async/await對(duì)mysql進(jìn)行封裝
這篇文章主要介紹了node基于async/await對(duì)mysql進(jìn)行封裝,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下2019-06-06