当前位置:网站首页>nodejs+Express+mongodb
nodejs+Express+mongodb
2022-04-22 06:43:00 【Bring in the red moon】
One 、 Create project
// Install scaffolding
$ npm install express-generator -g
// Create a project
$ express -e demo( Project name )
// Load dependencies
$ npm install
// Code real-time update ( Hot heavy load )
$ npm install nodemon -g
(1). install nodemon after Need modification package.json Start command in
{
"name": "mysql-demo",
"version": "0.0.0",
"private": true,
"scripts": {
//"start": "node ./bin/www" // There will be node Change it to nodemon
"start": "nodemon ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ejs": "~2.6.1",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"mongodb": "^4.1.3",
"morgan": "~1.9.1",
"nodemon": "^2.0.13"
}
}
(2).nodemon Installation successful And modify the startup command perform npm start start-up
$ npm start
(3). Additional records start-up mongodb database install mongodb Self search
// Specify the database directory Directory address
$ mongod --dbpath "D:\mongodb\data"
// After startup Open a new command line window Create the database required for the project
// perform Linked database
$ mongo
// Database basic command
show db // View all databases
user Database name // Enter the corresponding database ( There is no corresponding data to create )
db.dropDatabase() // Delete database ( You need to enter the corresponding database )
db.createCollection("users") // create documents " Document name "
show collections // View all documents in the current database
db.users.insertOne({name:'lory'}) // Insert a piece of data
db.users.find() // View all data in the current document
(4). install mongodb modular In the project file (demo) Folder command line window operation
$ npm install mongodb -s
(5). Create a new folder in the project after installation model Create a new... In this folder index.js file The content is
// establish mongo Client object
const MongoClient = require('mongodb').MongoClient;
// database Address
const url = 'mongodb://localhost:27017';
// Database name
const dbName = 'mongodb_demo'
// Database link method encapsulation
function connect(callback) {
MongoClient.connect(url, function (err, client) {
if (err) {
console.log(' Database link error ', err)
} else {
let db = client.db(dbName)
callback && callback(db)
}
})
}
module.exports = {
connect
}
(6). After the above steps are completed, find routes Under folder index.js When the file is opened Modify the content
var express = require('express');
var router = express.Router();
// Introduce the encapsulated linked database method
var model = require('../model')
/* GET home page. */
router.get('/', function (req, res, next) {
// Linked database
model.connect(function (db) {
// Find data in documents
db.collection('users').find().toArray(function (err, docs) {
console.log(" User list ", docs)
res.send({'msg':'S',data:docs}) // Interface to return
// res.render('index', { title: 'Express' }) // Templates
})
})
});
module.exports = router;
(7). Write an interface ( Example ) stay routes Found in file users.js open Edit content
var express = require('express');
var router = express.Router();
// Introduce the encapsulated linked database method
var model = require('../model')
/* GET users listing. */
router.get('/', function (req, res, next) {
res.send({ 'msg': 'S', data: [] })
});
// Here is the added content Each route can write multiple interfaces
/* register */
router.post('/regist', function (req, res, next) {
let data = {
username: req.body.username,
password: req.body.password,
password2: req.body.password2
}
if (!data.username) {
res.send({ 'msg': ' Please fill in your name ', code: 201 })
return
}
if (!data.password) {
res.send({ 'msg': ' Please fill in the password ', code: 201 })
return
}
if (data.password != data.password2) {
res.send({ 'msg': ' Password inconsistency ', code: 201 })
return
}
model.connect((db) => {
db.collection('users').insertOne(data, (err, ret) => {
if (err) {
console.log(' Registration failed ')
res.send({ 'msg': ' Registration failed ', code: 201 })
} else {
res.send({ 'msg': ' Registered successfully ', code: 200, data: data })
}
})
})
});
module.exports = router;
(8). open app.js file stay var app = express(); Add... After this line of code To prevent cross domain during testing
// Set up cross domain access
app.all("*",function(req,res,next){
// Set domain names that allow cross domain ,* Allows any domain name to cross domain
res.header("Access-Control-Allow-Origin","*");
// Allow the header type
res.header("Access-Control-Allow-Headers","content-type");
// How cross domain requests are allowed
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); // Give Way options Try to request a quick end
else
next();
})
(9). then Create a new front end html file ( Test interface ) The content is After writing, open in the browser View console
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$.ajax({
type: "post",
url: "http://localhost:3000/users/regist",
data: {
username: ' Liu Yi ',
password: '123',
password2: '123'
},
async: true,
success: function(res) {
console.log(res)
}
});
})
</script>
</html>
(10). Add route stay routes Add in folder .js file And then in app.js Add... To the file
// similar Introduced in this way
var usersRouter = require('./routes/users( New file name )');
app.use('/users'( The path of the corresponding interface ), usersRouter( New file name ));
This is probably the completion of There is a problem Self Baidu or leave a message
Two 、 The following record is a link mysql database
The above first 4 Step install mongodb modular Install... Instead mysql modular
$ npm install mysql
The code of step 5 above is changed to
// establish mysql Client object
let mysql = require("mysql");
const db_config = {
host: "localhost", // database ( The host address ) ( Default :localhost)
user: "root", // user name
password: "root",// password
port: "3000", // Port number
database: "testdb" // Database name
}
let sql = mysql.createConnection(db_config);
// Database link method encapsulation
function connect(callback) {
sql.connect(function (err) {
if (err) {
console.log(' Database link error ', err);
} else {
callback && callback(sql)
}
})
}
// Close after successful query mysql
function closeMysql(connect) {
connect.end((err) => {
if (err) {
console.log(`mysql Close the failure :${err}!`);
} else {
console.log('mysql Closed successfully !');
}
});
}
// // Basic query statements
// let sqlQuery = "select * from tb_user";
// sql.query(sqlQuery, function (err, result) {
// if (err) {
// console.log(`SQL error: ${err}!`);
// } else {
// console.log(result);
// closeMysql(connect);
// }
// });
module.exports = {
connect,
closeMysql
}
then routes Medium index.js Change the file to After modification open localhost:3000 see The rest modify the test yourself
var express = require('express');
var router = express.Router();
var model = require('../model')
/* GET home page. */
router.get('/', function (req, res, next) {
// res.render('index', { title: 'Express' });
// // Basic query statements
model.connect(function (db) {
let sqlQuery = "select * from tb_user";
db.query(sqlQuery, function (err, result) {
if (err) {
console.log(`SQL error: ${err}!`);
} else {
console.log(result);
model.closeMysql(db);
}
});
})
});
module.exports = router;
版权声明
本文为[Bring in the red moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220556230707.html
边栏推荐
- MySQL在面试中经常被问到的经典问题。
- COM in Wine(1)——COM基本概念
- PostgreSQL uses clickhousedb_ FDW access Clickhouse
- EXCEL 数据透视表的简单使用
- ArcMAP TIN与栅格DEM的坡度坡向对比分析
- 记一次 Redhat 6 yum无法使用的问题
- ArcGIS 观景点视域分析
- Spent four days painstakingly writing all the notes of MySQL, which is very suitable for beginners.
- JS get screen, browser, web page height and width
- 事务不生效之this调用
猜你喜欢

Cancel password after excel worksheet forgets password

创新实训(九)整合

Shumei technology and surging news jointly released the "network information content security insight report"

知网下载pdf(再也不想用CAJViewer啦!!!)

小程序调用扫描二维码功能并跳转到二维码指定的路径

剑指offer:数据流中的中位数(优先队列 大顶堆小顶堆 leetcode 295)

The display of redis stored data is garbled

ArcMAP TIN与栅格DEM的坡度坡向对比分析

Pixel手机电信4G破解(含解锁BL和root)

创新实训(五)配置信息
随机推荐
使用AES加密-复用前人的智慧
滚动条的多种样式
uniapp小程序锚点(只支持当前页面操作,切勿跨页面操作)
js,jq单行文字上下滚动
8张图让你一步步看清 async/await 和 promise 的执行顺序
Shumei technology was selected into the top 20 of Chaoyang high tech high growth in 2021
Click to trigger other DOM elements: < $refs, $El >
watch和computed的区别
JS, JQ single line text scrolling up and down
创新实训(六)路由
webService接口编写并发布与webService接口的调用(二)
Excel工作表忘记密码后取消密码
Shumei technology was honored as the "top 100 scientific and technological innovation of private enterprises in Beijing"
Wechat applet interface encapsulation (uniapp)
Differences between OLAP and OLTP and corresponding models (basic knowledge)
uglifyjs压缩JS
MYSQL事务之事务隔离级别
Pure JS chain animation and simultaneous motion
Usage rules of cast function in MySQL
Pgbackrest practice