欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

node.js+postman+mongodb搭建測(cè)試注冊(cè)接口的實(shí)現(xiàn)

 更新時(shí)間:2022年06月14日 10:43:12   作者:GottdesKrieges  
本文主要介紹了node.js+postman+mongodb搭建測(cè)試注冊(cè)接口的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

準(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用戶密碼淺析

    Node.js命令行/批處理中如何更改Linux用戶密碼淺析

    這篇文章主要給大家介紹了關(guān)于Node.js命令行/批處理中如何更改Linux用戶密碼的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-07-07
  • node.js做一個(gè)簡(jiǎn)單的爬蟲案例教程

    node.js做一個(gè)簡(jiǎn)單的爬蟲案例教程

    這篇文章主要介紹了node.js做一個(gè)簡(jiǎn)單的爬蟲案例教程,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • Node中解決接口跨域問題詳解

    Node中解決接口跨域問題詳解

    在 Node 中編寫接口時(shí),我們常常會(huì)遇到跨域問題,通過本篇文章,我們來聊聊如何解決 Node 中接口的跨域問題,文中代碼示例介紹了非常詳細(xì),需要的朋友可以借鑒一下
    2023-04-04
  • 說說如何利用 Node.js 代理解決跨域問題

    說說如何利用 Node.js 代理解決跨域問題

    這篇文章主要介紹了Node.js代理解決跨域問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • node.js操作mysql(增刪改查)

    node.js操作mysql(增刪改查)

    本文給大家分享的是使用node.js實(shí)現(xiàn)對(duì)mysql數(shù)據(jù)庫的增刪改查操作,有需要的小伙伴可以參考下,希望對(duì)大家學(xué)習(xí)node有所幫助。
    2015-07-07
  • express框架實(shí)現(xiàn)基于Websocket建立的簡(jiǎn)易聊天室

    express框架實(shí)現(xiàn)基于Websocket建立的簡(jiǎn)易聊天室

    本篇文章主要介紹了express框架實(shí)現(xiàn)基于Websocket建立的簡(jiǎn)易聊天室,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-08-08
  • 快速掌握Node.js模塊封裝及使用

    快速掌握Node.js模塊封裝及使用

    這篇文章主要為大家詳細(xì)介紹了Node.js模塊封裝及使用,幫助大家快速掌握Node.js模塊封裝及使用,感興趣的小伙伴們可以參考一下
    2016-03-03
  • Node綁定全局TraceID的實(shí)現(xiàn)方法

    Node綁定全局TraceID的實(shí)現(xiàn)方法

    這篇文章主要介紹了Node 綁定全局 TraceID的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • node基于async/await對(duì)mysql進(jìn)行封裝

    node基于async/await對(duì)mysql進(jìn)行封裝

    這篇文章主要介紹了node基于async/await對(duì)mysql進(jìn)行封裝,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下
    2019-06-06
  • node.js中Socket.IO的進(jìn)階使用技巧

    node.js中Socket.IO的進(jìn)階使用技巧

    這篇文章主要介紹了node.js中Socket.IO的進(jìn)階使用技巧,本文講解了配置、房間、事件、授權(quán)等內(nèi)容,需要的朋友可以參考下
    2014-11-11

最新評(píng)論