申请一个免费的MongoDB
到https://www.mlab.com注册申请一个500M的MongoDB数据库。登录后手动在创建Databases下的Collections中手动创建一个数据库node_app。
在个人首页点击Connect获取node.js连接MongoDB数据库的字符串为
1 | mongodb+srv:// |
将其中
到https://www.postman.com/注册一个账号,下载安装Postman agent,即可方便地进行GET/POST/PUT等测试。
安装mongoose用于连接数据库:
1 2 3 4 5 6 | > 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配置连接串:
1 2 3 | module.exports = { mongoURI: "mongodb+srv:// } |
编辑server.js入口文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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}`); }) |
检查是否能连接到数据库:
1 2 3 4 5 6 7 8 9 | > 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. |
数据库连接正常。
创建路由文件
1 | C:\Users\xiaoming\source\repos\node_demo\node_app\routes\api\users.js |
编辑users.js并添加GET请求:
1 2 3 4 5 6 7 8 9 | // 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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}`); }) |
访问
1 | http://localhost:5000/api/users/test |
可以看到
1 | {"msg":"Login succeeded!"} |
创建用户数据模型文件
1 | C:\Users\xiaoming\source\repos\node_demo\node_app\models\User.js |
编辑User.js创建用户数据模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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请求。
1 | > npm install body-parser |
编辑server.js使用body-parser:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // @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中测试:
1 | POST http://localhost:5000/api/users/register |
Body选择x-www-form-urlencoded,在KEY和VALUE中填入测试内容:
1 2 | 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包的用法介绍。
1 | > npm install bcrypt |
编辑users.js引入并使用User数据模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | // @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中填入测试内容:
1 2 3 | email godfrey@eldenring.com name godfrey password 123456 |
查看测试输出
1 2 3 4 5 6 7 8 | { "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请求插入的一条数据。
在gravatar - npm中查看gravatar的使用方法。
安装gravatar
1 | > npm i gravatar |
编辑users.js增加注册头像(avatar)处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | // @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中填入测试内容:
1 2 3 | email godfrey@eldenring.com name godfrey password 123456 |
测试会返回报错
1 2 3 | { "email": "Email already registered!" } |
在KEY和VALUE中填入测试内容:
1 2 3 | email mohg@eldenring.com name mohg password 123456 |
测试返回
1 2 3 4 5 6 7 8 9 | { "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 } |
现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。 如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受 可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛 分享他们的经验,还会分享很多直播讲座和技术沙龙 可以免费学习!划重点!开源的!!! qq群号:485187702【暗号:csdn11】
最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】
上一篇:最全的软件测试面试题(含答案)