链接: https://pan.baidu.com/s/1lw_qal0vcvGm3wiJC-F9xQ 提取码: ctj5 这里我提供一下我百度网盘的数据库安装包
可视化工具是为了便于管理数据库,根据个人喜好自行安装就行
上文中已经提到了怎么搭建node服务,现在来介绍如何连接数据库
在server.js文件夹中这样写
var express = require('express');
var app = express();
//设置跨域访问
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200); /*让options请求快速返回*/
} else {
next();
}
})
此时有个处理跨域的方法,否则会报跨域的错误
连接数据库,下面连接的是数据库的默认库,也可以自己建myList名字的库
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/runoob";
好接下来开始写接口,对数据库的增删改查
获取列表:
// 获取信息列表
app.get('/shujutongji', function (req, res) {
var data = [];
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
// var whereStr = {"name":'小明'}; // 查询条件
dbo.collection("CarList").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
res.send(result);
db.close();
})
});
});
增加数据
function successDate(msg, code,obj) {
const successData = {
code: code,
msg: msg,
data:obj
}
return successData
}
// 添加信息列表
app.get('/addPreson', function (req, resp) {
// var url = req.url;
var obj = {
name: req.query.name,
age: req.query.age,
sex: req.query.sex,
address: req.query.address,
height: req.query.height,
};
var flag = true
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("site").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
result.map((item, index) => {
if (obj.name == item.name) {
flag = false
console.log(flag)
}
})
if (flag) {
console.log(flag + 'sss')
dbo.collection("site").insertOne(obj, function (err, res) {
if (err) throw err;
console.log("文档插入成功");
resp.send(successDate('添加成功', 200))
db.close();
});
} else {
resp.send(successDate('不能添加同名信息', 400))
}
db.close();
})
});
});
删
//删除某条信息
app.get('/delete', function (req, resp) {
// var url = req.url;
var obj = {
name: req.query.name
};
console.log(obj)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("site").deleteOne(obj, function (err, obj) {
if (err) throw err;
console.log("文档删除成功");
resp.send(successDate('删除成功', 200))
db.close();
});
});
});
改
//更改密码
app.get('/changepwd', function (req, resp) {
// var url = req.url;
var user = {'userName':req.query.username}
var upPwd = {$set:{'passWord':req.query.pwd}}
console.log(user)
console.log(upPwd)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("userData").updateOne(user,upPwd, function (err, obj) {
if (err) throw err;
console.log("密码修改成功");
resp.send(successDate('密码修改成功', 200))
db.close();
});
});
});
post请求写法,这里以登录接口作为例子
//输后台接收账号密码进行判断,并返回数据
app.post("/login", function (req, resq) {
//定义一个空字符串
var query = '';
req.addListener("data", function (d) {
query += d;
// console.log(d);
})
var flag = true
//如果数据接收完毕
req.addListener('end', function () {
// 将字符串解析为对象
var params = require('querystring').parse(query);
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var whereStr = params // 查询条件
dbo.collection("userData").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
result.map((item, index) => {
if (params.userName == item.userName && params.pwd == item.passWord) {
var obj = item
resq.send(successDate('登录成功', 200,obj));
flag = false
}
})
if (flag) {
resq.send(successDate('用户名不存在', 400));
}
db.close();
})
});
})
});
在粘贴完整的server.js例子
var express = require('express');
var app = express();
//设置跨域访问
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200); /*让options请求快速返回*/
} else {
next();
}
})
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/runoob";
// 获取信息列表
app.get('/shujutongji', function (req, res) {
var data = [];
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
// var whereStr = {"name":'菜鸟教程'}; // 查询条件
dbo.collection("CarList").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
res.send(result);
db.close();
})
});
});
// 获取身份信息列表
app.get('/preson', function (req, res) {
var data = [];
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
// var whereStr = {"name":'菜鸟教程'}; // 查询条件
dbo.collection("site").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
res.send(result);
db.close();
})
});
});
// 获取城市列表
app.get('/cityList', function (req, res) {
var data = [];
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
// var whereStr = {"name":'菜鸟教程'}; // 查询条件
dbo.collection("cityList").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
res.send(result);
db.close();
})
});
});
function successDate(msg, code,obj) {
const successData = {
code: code,
msg: msg,
data:obj
}
return successData
}
// 添加信息列表
app.get('/addPreson', function (req, resp) {
// var url = req.url;
var obj = {
name: req.query.name,
age: req.query.age,
sex: req.query.sex,
address: req.query.address,
height: req.query.height,
};
var flag = true
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("site").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
result.map((item, index) => {
if (obj.name == item.name) {
flag = false
console.log(flag)
}
})
if (flag) {
console.log(flag + 'sss')
dbo.collection("site").insertOne(obj, function (err, res) {
if (err) throw err;
console.log("文档插入成功");
resp.send(successDate('添加成功', 200))
db.close();
});
} else {
resp.send(successDate('不能添加同名信息', 400))
}
db.close();
})
});
});
//删除某条信息
app.get('/delete', function (req, resp) {
// var url = req.url;
var obj = {
name: req.query.name
};
console.log(obj)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("site").deleteOne(obj, function (err, obj) {
if (err) throw err;
console.log("文档删除成功");
resp.send(successDate('删除成功', 200))
db.close();
});
});
});
//更改密码
app.get('/changepwd', function (req, resp) {
// var url = req.url;
var user = {'userName':req.query.username}
var upPwd = {$set:{'passWord':req.query.pwd}}
console.log(user)
console.log(upPwd)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("userData").updateOne(user,upPwd, function (err, obj) {
if (err) throw err;
console.log("密码修改成功");
resp.send(successDate('密码修改成功', 200))
db.close();
});
});
});
//登录窗口处理
//输后台接收账号密码进行判断,并返回数据
app.post("/login", function (req, resq) {
//定义一个空字符串
var query = '';
req.addListener("data", function (d) {
query += d;
// console.log(d);
})
var flag = true
//如果数据接收完毕
req.addListener('end', function () {
// 将字符串解析为对象
var params = require('querystring').parse(query);
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var whereStr = params // 查询条件
dbo.collection("userData").find().toArray(function (err, result) { // 返回集合中所有数据
if (err) throw err;
result.map((item, index) => {
if (params.userName == item.userName && params.pwd == item.passWord) {
var obj = item
resq.send(successDate('登录成功', 200,obj));
flag = false
}
})
if (flag) {
resq.send(successDate('用户名不存在', 400));
}
db.close();
})
});
})
});
// app.get("*", function(req, res) {
// res.sendFile(`${__dirname}/view${req.url}`);
// })
app.listen(8889, 'localhost', function() {
console.log('服务器开启成功');
})