node相关

nodejs学习笔记

2020-01-14  本文已影响0人  zyghhhh

为什么要学习nodejs

因为这是一门后台开发语言,用js来写得后台语言,使用ecma规范,前端人员学习起来不用再从基础得语法知识学起比较快上手,当代前端也需要了解后端开发是在什么,甚至有一些原本由后端处理得工作现在已经是前端在做了,所以前端也需要懂得后端知识(更直接说也是为了升职加薪 哈哈)

  1. 分别暴露方式(把要暴露得东西当成exports对象得属性暴露出去,通过require引入)

    • 暴露 exports.xxx = xxx
    • 引入 xxx = require('/path')
  2. 默认暴露方法

    • 暴露 module.exports.xxx = xxx

注意:这两种方法暴露出去得东西都会在添加在一个对象中,也就是说引入时引入得的是一个对象,数据都在这个对象上面。但是,当exports和module.exports 暴露的时候指向的不是一个对象的话,会以module.exports暴露的为准。

  1. mongoose: nodejs要通过这个模块才可以操作mongodb数据库
 * 创建服务 的步骤
 * 1 需要引入使用nodejs中提供的系统模块 http,并且创建服务器对象 需要调用http模块的createServer()方法
 * 2 处理请求 返回相应
 * 3 监听端口号
 * 4 打印运行
 *
 * 访问方法: 通过localhost:端口号
 */

    //引入Http模块
 const http = require('http')
 //创建一个服务器对象
 const app = http.createServer()

 //服务器对象.on 第一个参数用来绑定处理客户端的请求的时间,通过第二个参数回调函数返回响应
app.on('request',(req,res) => {

     //设置返回的响应格式为utf-8,Http状态码是200  不写这个会乱码
     res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });

     //res.end 用来返回响应的
     res.end('<h2>这是服务器返回的一串字符</h2>')
 })

 // 监听端口号
 app.listen(3000)

 console.log('服务器启动成功')
  1. await
  1. node中处理异步需要用到util模块中的方法,这个在第三方模块目录中有说明,请往上翻
//1 创建集合规则 使用mongoose.Schema()方法传入一个对象写明规则,也就是有哪些字段
const courseSchema = new mongoose.Schema({
    //所谓集合规则也就是数据库中都有哪些字段,写在对象中传入
    name:String,
    author:String,
    isPublished:Boolean
})

//2 创建集合
//步骤:1定义集合规则 2创建集合 3向集合中插入文档
/**
 * mongoose.model()方法创建集合,传两个值
 * 1 集合名称首字母要大写
 * 2 集合规则实例,要根据这个去创建集合中的规则都有哪些字段
 * 3 mongoose.model()创建文档,第一个参数是文档名字,这个方法返回的是一个构造函数 这个构造函数就代表这个集合,第一个
 *  */  
const Course = new mongoose.model('Course',courseSchema)

//3 向集合中插入文档,要用集合的实例去调用save()方法
const course = new Course({
    //向实例对象中传入对象写明数据,这个对象就是数据库中的文档document
    name:'node.js课程',
    author:'大宝',
    isPublished:true
})

//保存进数据库
course.save();

// 第二种插入文档的方式 推荐这个
// 集合实例.create()  两个参数 1 要插入的文档数据  2回调函数,插入完成会调用
Course.create({name:'javascript',author:'二宝',isPublished:false})
              .then(result => console.log(result))
              .catch(err => console.log(err))
    //查找删除一条文档  打印返回的是删除的文档
    User.findOneAndDelete(obj).then(res => console.log(res)) 传入删除条件
    
    // 删除多条文档,打印返回的是一个对象,里面会有n 和 ok,n代表删除的数量,ok代表操作成功
    // 如果条件不传或者是空对象就会删除所有的数据 慎用!!! 
    User.deletMany(obj).then(res => console.log(res)) 删除多个,如果是个空对象
    语法:
          User.updateOne({查询条件},{要修改的值}).then(res => console.log(res))
          User.updateMany({查询条件},{要修改的值}).then(res => console.log(res))
    例子:  
          //修改一条
          User.updateOne({name:'李四'},{name:'李狗蛋'}).then(res => console.log(res))
          //修改多条 如果查询条件是空对象就会修改所有的 
          User.updateOne({},{age:18}).then(res => console.log(res))
const mongoose = require('mongoose')


mongoose.connect('mongodb://localhost:test',{useUnifiedTopology:true,useNewUrlParser:true})
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'))


//创建集合规则
const personSchema =   new mongoose.Schema({
    title:{
        //minlength  maxlength针对字符串类型
        type:String,   //类型 字符串
        required:[true,'请传入title'],   //必传,数组中第二个值是自定义的错误提示
        minlength:[2,'最小长度是2'],    //最小长度为2,数组中第二个值是自定义的错误提示
        maxlength:[5,'最5大长度是5'],   //最大长度为5,数组中第二个值是自定义的错误提示
        trim:true
    },
    age:{//年龄
        //min max最大值最小值 针对数值类型
        type:Number,  //
        min:[18,'不能小于18'],   //最小18
        max:[60,'不能大于60']    //最大60
    },
    publisDate:{//时间   
        type:Date, //时间类型
        default:Date.now  //设置了默认时间,传入的时候不传也可以
    },
    category:{//分类
        type:String,
        //分类 这个会枚举属性值 也就是数组,判断传入的是不是数组中的值,不是的话传入失败
        enum:{
            values:['html','css','js'], //传入的值的类型
            messages:'传入的category值不符合规则' //自定义错误信息
        }
    },
    author:{//自定义判断规则
        type:String,
        validate:{ //自定义判断规则
            validator: v => {
                // 1 要返回布尔值
                // 2 true验证成功
                // 3 false验证失败
                // v 要验证的值
                return v && v.length > 4
            },
            //自定义错误信息
            message:'传入的值不符合验证规则'
        }
    }
})

// 创建集合   3个值: 1标识,2规则,3集合名字  
const Person = mongoose.model('Person',personSchema,'Person')

//插入文档
Person.create({title:'标题',age:21,category:'js',author:'zyghhhh'})
.then(res => console.log(console.log(res,'插入成功')))
.catch((error) => {
    //这里的代码是要获取错误信息  是只打印错误的提示信息
    var err = error.errors
    //每个错误信息都是一个对象,错误提示是message 
    //都存在error中 error也是一个对象,所以通过枚举拿到每个对象中的message 
    for(var attr in err){
        console.log(err[attr]['message'])
    }
})
// 集合关联模块


const mongoose =  require('mongoose')



// 连接数据库
mongoose.connect('mongodb://localhost:test2',{useUnifiedTopology:true,useNewUrlParser:true})
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'))

//创建用户集合规则
const UserSchema = new mongoose.Schema({name:String})

//创建文章集合规则
const PostSchema = new mongoose.Schema({title:String,author:{
    /**
     * mongoose.schema.Types.ObjectId 这串可以拿到每条数据的_id 这是一个特殊的类型
     * 做法: 
     *      1.读取_id 
     *      2.指定要关联那个表 
     *      3.使用mongoose.find().populate('数据名') 就可以读取到了,代码就是最后一行
     */    
    type:mongoose.Schema.Types.ObjectId,  //读_id
    ref:'User'    //指定要关联的集合
}})



//创建用户集合
const User = mongoose.model('User',UserSchema,'User')
//创建文章集合
const Post = mongoose.model('Post',PostSchema,'Post')


User.create({name:'三宝'}).then(res => console.log(res,'数据插入成功'))
Post.create({title:'红楼梦',author:'5e17ec3f9f9e2c2ad89e6cb2'}).then(res => console.log(res,'数据插入成功'))


Post.find().populate('author').then(res => console.log(res))

art-template:第三方模块,作用是数据和摸版拼接在一起

  1. 下载引入这个模块,这个模块返回的是一个方法,这个方法传2个值
    • 值1: 摸版的路径 摸版必须是.art后缀,里面写的html代码,路径要用绝对路径,建议使用path模块的path.join()拼接
    • 值2: 数据,对象形式
  2. 使用:在摸版中{{}}这样就可以读取数据,比如

const template = require('art-template')

const path = require('path')

// template模块暴露的是一个方法可以把摸版和数据进行拼接
// 2个值  1: 摸版路径 2:数据
const html = template(path.join(__dirname,'views','index.art'),{
    name:'张三',
    age:20
})

console.log(html)
  1. use中间件可以接受所有的请求,然后根据这个特性可以做出判断
  2. use中间件的使用场景有很多,比如路由保护,网站维护,自定义404页面
//把静态资源目录public放在
// 值1:指定一个虚拟路由路径, 值2:静态资源文件夹目录 绝度路径
app.use('/static',express.static(path.join(__dirname,'public')))
  1. 错误捕获: 可以使用 try catch配合使用, 代码会先执行try中的代码 如果有错,会给catch传递一个参数,在catch中把调用next()错误传递给错误处理中间件,这样页面不会报错,后台可以捕获到错误
app.get('/index',async (req,res,next) => {
    try{
        /**
         * const promisify = require('util').promisify

           const readFile = promisify(fs.readFile)     
           readFile是这么包装过的,还是用来读取文件的
         * 
         */
        await readFile('./aa.js')
    }catch (ex) {
        next(ex);
    }
})

//错误捕获中间件
app.use((err,req,res,next) => {
    res.status(500).send(err.message)
})
上一篇 下一篇

猜你喜欢

热点阅读