nodejs學習筆記

來源:互聯網
上載者:User

標籤:檔案   名稱   use   內容   create   互動   query   word   擷取   

## 模組化 ##

    每一個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){
    
   })
   



 

nodejs學習筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.