標籤:檔案 名稱 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學習筆記