node.js+postman+mongodb搭建測試注冊接口的實現(xiàn)
準(zhǔn)備工作
申請一個免費(fèi)的MongoDB
到https://www.mlab.com注冊申請一個500M的MongoDB數(shù)據(jù)庫。登錄后手動在創(chuàng)建Databases下的Collections中手動創(chuàng)建一個數(shù)據(jù)庫node_app。
在個人首頁點(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/注冊一個賬號,下載安裝Postman agent,即可方便地進(jìn)行GET/POST/PUT等測試。
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請求測試
創(chuàng)建路由文件
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,導(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!"}
注冊接口搭建
創(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請求。
> 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請求測試
編輯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中填入測試內(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可以用來加密注冊用戶的密碼,避免在數(shù)據(jù)庫中存儲明文密碼。在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: "郵箱已被注冊!" })
? ? ? ? ? ? } 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中填入測試內(nèi)容:
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中查看,會發(fā)現(xiàn)多出了一個users的Collection,其中剛好存儲了上面我們剛通過POST請求插入的一條數(shù)據(jù)。
使用gravatar處理頭像
在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中填入測試內(nèi)容:
email ? ? godfrey@eldenring.com name ? ? ?godfrey password ?123456
測試會返回報錯
{
"email": "Email already registered!"
}
在KEY和VALUE中填入測試內(nèi)容:
email mohg@eldenring.com name mohg password 123456
測試返回
{
"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搭建測試注冊接口的實現(xiàn)的文章就介紹到這了,更多相關(guān)node postman mongodb注冊接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js命令行/批處理中如何更改Linux用戶密碼淺析
這篇文章主要給大家介紹了關(guān)于Node.js命令行/批處理中如何更改Linux用戶密碼的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07
express框架實現(xiàn)基于Websocket建立的簡易聊天室
本篇文章主要介紹了express框架實現(xiàn)基于Websocket建立的簡易聊天室,具有一定的參考價值,有興趣的可以了解一下2017-08-08
node基于async/await對mysql進(jìn)行封裝
這篇文章主要介紹了node基于async/await對mysql進(jìn)行封裝,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,,需要的朋友可以參考下2019-06-06

