nodejs学习笔记

## 模块化 ##

    每一个js文件就是一个模块
    每个模块就是一个单独的作用域

依赖和依赖注入

一样东西要依赖另外一样东西才能运行

如jquery依赖的是jquery的js文件,handlebar模板引擎依赖handlebars.js文件
如 js文件依赖于js解析引擎

module.exports.xxx = xxx;
commonjs规范通过module.exports来暴露模块里的xxx

**在app.js文件里**

1.require('路径')来接收这个暴露,引入文件
var b = require(b.js)

2.设置路由
 app.use('/b', b);


www是nodejs的启动文件

    public 文件夹放项目静态文件
    routes 路由,内容分发

req.query 拿到前端传过来的name名字(请求头,得到get)
req.body 拿到前端传过来的name名字(请求体,得到post)

res.send() 发送内容
res.sendfile()发送文件/页面

交互步骤
1.在public 静态文件夹下创建提交交互的页面
2.在action 下设置处理的文件路径
3.更改users.js里的
   
   `router.post('/log',function(req,res,next){`
     if(req.body.userName==='zs'&&req.body.password=== '123456'){
         res.sendfile('./public/success.html')
     }else{
         res.sendfile('./public/fail.html')
     }
    })

     post — 只提交表单时的方式 get/post
     'log' — 自己配置的表单提交路径
     req — 请求
     res — 响应
     send() — 响应后返回字符串
     sendfile() — 响应后返回文件(html等)
     req.query.username — 接收请求时在头部(query)里获取到'get'方式
     并且获取到提交的name.
     req.body.username — 接收请求时在身体(body)里获取到'post'方式,并且获取到提交的name.


连接数据库

 1.复制文档里的连接方式

 2.设置数据类型的结构
  schema 结构 :用来描述数据类型的结构,如name = string password=string
 ** 例:**
  var userSchema = new mongoose.Schema({
      name:'string',
      passwored:'string'
   })

 3.创建model模型
   mongoose.model(模型名称,模型对应的结构schema,mongodb里对应的文档名)
   mongoose.model('user',userSchema,'userCollection')

 4.在触发某个路径的时候,会操作数据库,如新增数据
   var userModel = mongoose.model('users');
   mongoose.create({
      userName:req.body/query.userName,
      password:req.body/query.password
    },function(err,data){
    
   })
   



 

原文地址:https://www.cnblogs.com/luowen075/p/6060230.html