一、node服务器
能够提供网站服务的机器就是网站服务器,它能够接受客户端的请求,能够对请求做出响应。
[1].创建服务器
-
创建app.js文件
//用于创建网站服务器的模块 const http = require('http'); //app对象就是网站服务器对象 const app = http.createServer(); //当有客户端请求来的时候,会触发on方法, //在事件处理函数中有两个参数,request和response app.on('request', (req, res) => { //对客户端进行响应 res.end('<h2>hello user<h2>') }); //监听一个端口 app.listen(3000); console.log('服务器启动成功');
-
启动服务器
在控制台中进入到app.js所在的文件中node app.js
-
在浏览器中输入:localhost:3000
[2]. 客户端请求
app.on('request', (req, res) => {
req.headers // 获取请求报文
req.url // 获取请求地址,包括get请求中的参数
req.method // 获取请求方法,post、get等
});
[3]. 服务端响应
内容类型:
- text/html
- text/css
- application/javascript
- image/jpeg
- application/json
app.on('request', (req, res) => {
// 设置响应报文
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf8'
});
});
[4]. 获取请求参数
- get请求
const http = require('http'); // 导入url系统模块 用于处理url地址 const url = require('url'); const app = http.createServer(); app.on('request', (req, res) => { //console.log(url.parse(req.url)); // 将url路径的各个部分解析出来并返回对象 // true 代表将参数解析为对象格式 let {query} = url.parse(req.url, true); console.log(query); }); app.listen(3000);
- post请求
const http = require('http'); //将字符串转换为对象 const app = http.createServer(); // 导入系统模块querystring 可以将字符串转换为对象 const querystring = require('querystring'); app.on('request', (req, res) => { //post参数是通过事件的方式接受的 //data 当请求参数传递的时候发出data事件 //end 当请求参数传递完成的时候发出end事件 //这么做的原因是post请求的数据量是不限制的 let postData = ''; // 监听参数传输事件,params是post传递过来的参数 req.on('data', (params) => postData += params;); // 监听参数传输完毕事件 req.on('end', () => { //调用parse方法将参数转换为对象 console.log(querystring.parse(postData)); }); });
[5]. 获取静态资源
需要安装mime模块,来辨别请求文件的类型
https://www.npmjs.com/package/mime
返回给客户端请求的静态页面
const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime');
const app = http.createServer();
let info = ''
app.on('request', (req, res) => {
req.url = req.url === '/' ? '/default.html' : req.url;
const realPath = path.join(__dirname, 'public', req.url);
fs.readFile(realPath, (err, data) => {
if (err) {
res.writeHeader(404, {
'content-type': 'text/html;charset=utf8'
})
res.end('读取数据失败'+ realPath);
return
} else {
//即使不写该项在高级浏览器中也可以正确分辨文件类型
res.writeHeader(200,{
'content-type':mime.getType(realPath)+';charset=utf8'
})
res.end(data);
}
})
})
app.listen(3000);
console.log('服务启动');
[6]. 密码加密
密码加密bcrypt依赖环境
-
1.安装python 2.x环境用于密码加密 python-2.7.10.amd64.msi 将安装目录放入电脑的环境变量
-
2.node-gyp
npm install -g node-gyp -
3.windows-build-tools
npm install --global --production windows-build-tools
出现Python 2.7.15 is already installed, not installing again代表安装成功 -
4.新建一个命令行工具,否则python环境变量不会生效
-
5.安装bcrypt
npm install bcryptconst bcrypt = require('bcrypt'); async function run() { //生成随机字符串 //genSalt方法接受一个数值作为参数,数值越大,生成的随机字符串越复杂 const salt = await bcrypt.genSalt(10); //对密码进行加密 // 参数1: 要进行加密的明文 // 参数2: 随机字符串 // 返回加密的密码 const result = await bcrypt.hash('123456', salt) console.log(result); //密码比对 //参数1: 明文密码 //参数2: 加密密码 //返回布尔值 let isEqual = await bcrypt.compare('123456', '$2b$10$uSdIyyLZs2ijEAUnGz/o/OpUpiHcgku4pinox6ruZIKtgS7HHarQ6') console.log(isEqual); } run();
二、mongoDB数据库
[1].下载安装mongoDB
同时下载mongoDB的可视化软件。
https://www.mongodb.com/download-center/community
mongoose文档:
https://mongoosejs.com/
http://www.mongoosejs.net/
[2]. node连接mongoDB
-
下载mongoose第三方包
npm install mongoose
-
在命令行工具中启动mongoDB
net start mongoDB
-
连接数据库
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log("连接成功"); }).catch((err) => { console.log('连接失败', err); });
[3]. 插入数据
//设定要插入数据的规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
//创建集合并应用规则,会在playground创建一个courses表
const Course = mongoose.model('Course', courseSchema)
Course.create({ name: 'Javascript', author: '李四', isPublished: false })
.then(result => {
console.log(result)
}).catch(err => {
console.log(err);
});
[4]. 导入数据
mongodb已经在环境变量的前提下。
mongoimport -d 数据库名称 -c 集合名称(表名称) --file 要导入的数据文件
[5]. 查询数据
https://mongoosejs.com/docs/api/query.html#query_Query-limit
//设定集合规则
const courseSchema = new mongoose.Schema({
_id: String,
name: String,
age: Number,
hobbies: Array,
email: String
});
//创建集合并应用规则,查询的是User表,在mongodb中为“users”表
const Course = mongoose.model('User', courseSchema);
Course.find().then(result => console.log(result));
[6]. 删除数据
//设定集合规则
const courseSchema = new mongoose.Schema({
_id: String,
name: String,
age: Number,
hobbies: Array,
email: String
});
//创建集合并应用规则,会在playground创建一个courses表
const User= mongoose.model('User', courseSchema);
//删除姓名为张三的数据,删除成功,会将删除的数据返回
User.findOneAndDelete({name:'张三'}).then(result=>{
console.log(result);
});
[7]. 修改数据
// 更新单个
User.updateOne({查询条件}, {要修改的值}).then(result => console.log(result))
// 更新多个
User.updateMany({查询条件}, {要更改的值}).then(result => console.log(result))
//设定集合规则
const courseSchema = new mongoose.Schema({
_id: String,
name: String,
age: Number,
hobbies: Array,
email: String
});
const User = mongoose.model('User', courseSchema);
//将id为5ee9b1057c465c36602f5e17的名字改为张三
User.updateOne({_id:'5ee9b1057c465c36602f5e17'},{name:'张三'}).then(result=>{
console.log(result);
});
[8]. 数据验证
http://www.mongoosejs.net/docs/validation.html#unique-%E4%B8%8D%E6%98%AF%E9%AA%8C%E8%AF%81%E5%99%A8
//创建schema
var schema = new mongoose.Schema({
name: {
//输入的类型
type: String,
// 必填选项
required: [true, 'name为必填选项'],
// 最小/大长度
minlength: [2, 'name最小长度为2'],
maxlength: [5, 'name最大长度为5'],
// 去除文字两端空格
trim: true
},
author: {
type: String,
validate: {
// 返回布尔值,true 验证成功,false验证失败,
// v要验证的值
validator: v => {
return v && v.length > 4
},
// 自定义验证规则
message: '传入的值不符合验证规则'
}
},
category: {
type: String,
enum:{
values: ['coffee', 'tea'],
message:'分类超出了范围'
}
}
});
//将schema编译成一个model
var Model = mongoose.model('Post', schema);
Model.create({ name: 'Javas', author: '',category:'apple'})
.then(result => {
console.log(result)
}).catch(e => {
// 捕获所有的错误信息
// console.log(e.errors.author.properties.message);
const err = e.errors
for (let item in err) {
console.log(item + '的错误信息为:', err[item].properties.message);
}
});
[9]. 集合关联
http://www.mongoosejs.net/docs/populate.html
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
var Schema = mongoose.Schema;
var personSchema = Schema({
name: String,
age: Number,
});
var storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
//创建personSchema实例
Person.create({ name: '张三', age: 15 }).then(result => {
console.log(result._id);
Story.create({author: result._id, title:'java'})
});