这篇文章主要讲解了“node.js+postman+mongodb如何搭建测试注册接口”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“node.js+postman+mongoDB如何搭建测试
这篇文章主要讲解了“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 5000MongoDB connected.
数据库连接正常。
创建路由文件
C:\Users\xiaoming\source\repos\node_demo\node_app\routes\api\users.js
编辑users.js并添加GET请求:
// login & reGISttrationconst 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!");})// 使用usersapp.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 ScheMaconst 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 & registtrationconst express = require("express");const router = express.Router();router.get("/test", (req,res) => { res.json({msg:"Login succeeded!"})})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 VALUEemail 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 & registtrationconst express = require("express");const router = express.Router();const bcrypt = require("bcrypt");const User = require("../../models/User.js");router.get("/test", (req,res) => { res.json({msg:"Login succeeded!"})})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.comname godfreypassword 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 & registtrationconst express = require("express");const router = express.Router();const bcrypt = require("bcrypt");const gravatar = require("gravatar");const User = require("../../models/User.js");router.get("/test", (req,res) => { res.json({msg:"Login succeeded!"})})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.comname godfreypassword 123456
测试会返回报错
{ "email": "Email already registered!"}
在KEY和VALUE中填入测试内容:
email mohg@eldenring.comname mohgpassword 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如何搭建测试注册接口这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!
--结束END--
本文标题: node.js+postman+mongodb如何搭建测试注册接口
本文链接: https://lsjlt.com/news/340760.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0