您好,登錄后才能下訂單哦!
這篇文章主要講解了“node.js+postman+mongodb如何搭建測試注冊接口”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“node.js+postman+mongodb如何搭建測試注冊接口”吧!
申請一個免費的MongoDB
到https://www.mlab.com
注冊申請一個500M的MongoDB數據庫。登錄后手動在創建Databases下的Collections中手動創建一個數據庫node_app。
在個人首頁點擊Connect獲取node.js連接MongoDB數據庫的字符串為
mongodb+srv://<username>:<password>@cluster0.ylpaf.mongodb.net/node_app
將其中<username>:<password>修改為自己設定的數據庫用戶名和密碼。
到https://www.postman.com/
注冊一個賬號,下載安裝Postman agent,即可方便地進行GET/POST/PUT等測試。
安裝mongoose用于連接數據庫:
> 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}`); })
檢查是否能連接到數據庫:
> 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.
數據庫連接正常。
創建路由文件
C:\Users\xiaoming\source\repos\node_demo\node_app\routes\api\users.js
編輯users.js并添加GET請求:
// 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,導入并使用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)); // 設置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:\Users\xiaoming\source\repos\node_demo\node_app\models\User.js
編輯User.js創建用戶數據模型:
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中間件,可以方便地處理HTTP請求。
> 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}`); })
編輯users.js增加POST請求:
// @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中暫時只有一個打印請求體的操作。
在Postman中的Workspace中測試:
POST http://localhost:5000/api/users/register
Body選擇x-www-form-urlencoded,在KEY和VALUE中填入測試內容:
KEY VALUE email harlie@google.com
查看終端輸出:
Server running on port 5000
MongoDB connected.
[Object: null prototype] { email: 'harlie@google.com' }
說明成功獲取到了req.body。
首先安裝bcrypt包。bcrypt可以用來加密注冊用戶的密碼,避免在數據庫中存儲明文密碼。在https://www.npmjs.com/上可以查看bcrypt包的用法介紹。
> npm install bcrypt
編輯users.js引入并使用User數據模型:
// @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: "郵箱已被注冊!" }) } 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中測試POST http://localhost:5000/api/users/register。Body選擇x-www-form-urlencoded,在KEY和VALUE中填入測試內容:
email godfrey@eldenring.com name godfrey password 123456
查看測試輸出
{ "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中查看,會發現多出了一個users的Collection,其中剛好存儲了上面我們剛通過POST請求插入的一條數據。
在https://www.npmjs.com/package/gravatar中查看gravatar的使用方法。
安裝gravatar
> npm i gravatar
編輯users.js增加注冊頭像(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中測試POST http://localhost:5000/api/users/register,Body選擇x-www-form-urlencoded。
在KEY和VALUE中填入測試內容:
email godfrey@eldenring.com name godfrey password 123456
測試會返回報錯
{ "email": "Email already registered!" }
在KEY和VALUE中填入測試內容:
email mohg@eldenring.com name mohg password 123456
測試返回
{ "name": "mohg", "email": "mohg@eldenring.com", "password": "$2b$10$uSV2tmA5jH6veLTz1Lt5g.iD5QKtbJFXwGsJilDMxIqw7dZefpDz.", "avatar": "//www.gravatar.com/avatar/c5515cb5392d5e8a91b6e34a11120ff1?s=200&r=pg&d=mm", "_id": "62a44f12d2c5293f0b8e9c2b", "date": "2022-06-11T08:15:14.410Z", "__v": 0 }
在瀏覽器中打開
感謝各位的閱讀,以上就是“node.js+postman+mongodb如何搭建測試注冊接口”的內容了,經過本文的學習后,相信大家對node.js+postman+mongodb如何搭建測試注冊接口這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。