天天看點

node學習筆記-好程式員

一、NodeJS如何連結mongodb

NodeJS中連結Mongodb

1、安裝

cnpm install mongodb -S

2、建立連結的位址

3、連結

const mongoClient = require("mongodb").MongoClient;​//2、建立連結的方式const url = "mongodb://127.0.0.1:27017";​//3、建立連結的資料庫const db_name = "gp17";​//4、連結mongoClient.connect(url,(err,client)=>{

if(err){
    console.log("連結失敗")
}else{
    console.log("連結成功")
    //5、連結資料庫以及表        var user = client.db(db_name).collection("user");
}})           

二、mongoose的基本使用

1、mongoose與mongodb的差別

參考上面的

2、NodeJS連結mongoose

const mongoose = require('mongoose');//是一個構造函數 用來限制表的字段類型const Schema = mongoose.Schema;//連結的位址const url = "mongodb://127.0.0.1:27017/gp17";​//連結mongoose.connect(url,(err)=>{

if(err){
    console.log("連結失敗");
}else{
    console.log("連結成功")
}})​//連結表/建立表var StudentsSchema = new Schema({
sname:String,
sage:Number})//傳回值是一個構造函數const Students = mongoose.model("student",StudentsSchema);//如果表的名稱是複數則 資料庫中的表名稱不會變 如果不是複數則資料庫中标的名稱會自動加s​// mongoose.model("students",{//     sname:String,//     sage:Number// })           

三、用所封裝好的路由+nodeJS+Mongoose+MVC實作登入注冊

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./css/index.css"></head><body>
<h1>index頁面</h1>
<div>
    <img src="./img/u=2071817741,4218539796&fm=58&s=EE7A2FC0DE0120D6CF6D1509010070D2.jpg" alt="">
    <img src="./img/u=2708490274,319030395&fm=58&s=9E3269850EF36DB70811A15B03008060.jpg" alt="">
    <img src="./img/u=3473750589,1700978550&fm=58&s=4E946D84D2417CFE5C3FB5D90300D0B9.jpg" alt="">
    <img src="./img/u=3508817781,1654561115&fm=58&s=6D83639716736DB3087070600300E070.jpg" alt="">
</div>           

<form id="user">
    使用者名: <input type="text" id="username">
    密碼: <input type="text" id="password">
    <input type="submit">
</form></body></html><script src="./js/index.js"></script><script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.js"></script>           
$("#user").on("submit",function (e) { 
    e.preventDefault()
    var username = $("#username").val();
    var password = $("#password").val();​​
    $.ajax({
        url:"/user/register",
        method:"post",
        data:{
            username,
            password
        },
        success:function(data){
            console.log(data);
        }
    })
})​</script>
           

const http = require("http");const router = require("./router")const server = http.createServer(router)​router.post("/user/register",(req,res)=>{

console.log(req.body);​           

res.json({

code:200,
   errMsg:''           

})})​​server.listen(9000)​const url = require("url");const fs = require("fs");const path = require("path");const qs = require("querystring")//收集事件const routerMap = {

get:{},
post:{}}​const router = function(req,res){
//給res添加一個json方法    res.json = function(obj){
    res.end(JSON.stringify(obj))
}​
//處理靜态資源    handleStatic(req,res);​​
//擷取使用者請求的方式    var method = req.method.toLowerCase();
//擷取使用者請求的位址    var {pathname,query} = url.parse(req.url,true);​
if(method === "get"){
    if(routerMap.get[pathname]){
        //将query的值指派給req.query            req.query = query;
        routerMap.get[pathname](req,res)
    }else{
        res.end("404")
    }​​
}else if(method === "post"){
    if(routerMap.post[pathname]){
        var str = "";​
        //擷取post傳遞的參數            req.on("data",(data)=>{
            str += data;
        })​
        req.on("end",()=>{
           req.body = qs.parse(str);
           routerMap.post[pathname](req,res)
        })
        
    }
}}​//注冊事件router.get = function(path,callback){
routerMap.get[path] = callback;}//注冊事件router.post = function(path,callback){
routerMap.post[path] = callback;}​​​//處理所有的靜态資源通路function handleStatic(req,res){
var {pathname} = url.parse(req.url,true);
//擷取檔案的字尾    var ext = pathname.substring(pathname.lastIndexOf("."));​
if(pathname ==="/"){
    res.writeHead(200,{"content-type":"text/html;charset=utf8"});
    res.end(getFile(path.join(__dirname,"../public/index.html")))
}else if(ext === ".css"){
    res.writeHead(200,{"content-type":"text/css;charset=utf8"});
    res.end(getFile(path.join(__dirname,"../public",pathname)));
}else if(ext === ".js"){
    res.writeHead(200,{"content-type":"application/x-javascript;charset=utf8"});
    res.end(getFile(path.join(__dirname,"../public",pathname)));​
}else if(/.*\.(jpg|png|gif)/.test(ext)){
    res.writeHead(200,{"content-type":`image/${RegExp.$1};charset=utf8`});
    res.end(getFile(path.join(__dirname,"../public",pathname)));
}else if(ext === ".html"){
    res.writeHead(200,{"content-type":"text/html;charset=utf8"});
    res.end(getFile(path.join(__dirname,"../public",pathname)));
}}​​function getFile(filePath){
return fs.readFileSync(filePath);}​module.exports = router;           

四、express的基本入門

1、什麼是express?

Express 是一個保持最小規模的靈活的 Node.js Web 應用程式開發架構,為 Web 和移動應用程式提供一組強大的功能

2、什麼是中間件

請求和回複之間的一個應用

3、常見的中間件有哪些?

1、應用層中間件(http請求之類的應用)

const express = require("express");const app = express();​//應用層的中間件app.use((req,res,next)=>{

console.log(123);

next()})​app.use((req,res,next)=>{

console.log(456)

console.log(789);

next();})​app.use("/home",(req,res,next)=>{

res.end("home");})​app.get("/list",(req,res,next)=>{

res.end("list")})​app.post("/list",(req,res,next)=>{

res.end("list")})​​app.listen(9000,()=>{

console.log("server address:127.0.0.1:9000")})​/ express中的中間件會分為哪幾類? 1、應用層中間件(http請求之類的應用) app.use app.get app.post​​ 2、内置中間件 3、錯誤進行中間件 4、路由中間件 5、第三方中間件 6、自定義中間件​​ 如何使用中間件? app.use(中間件) 使用中間件​ app.use中的參數 path:選填 callback || router​ 如果是callback的請求下 這個回調中會有3個參數 req:請求 res:響應 next:執行下一個中間件​​ 隻要http這個服務跑一次那麼久會将app.use中的所有函數統一執行一遍/

2、内置中間件

const express = require("express");const app = express();const path = require("path");//内置中間件app.use(express.static(path.join(__dirname,"./public")))​​app.listen(9000,()=>{

console.log("server address:127.0.0.1:9000")})

3、錯誤進行中間件

const express = require("express");const app = express();const path = require("path");//内置中間件app.use(express.static(path.join(__dirname,"./public")))​​​//錯誤中間件處理一般寫在程式的最後面app.use((req,res,next)=>{

res.status(404).send("沒有這個頁面")})​app.listen(9000,()=>{

4、路由中間件

const express = require("express");const app = express();const path = require("path");const indexRouter = require("./router/index");​//内置中間件app.use(express.static(path.join(__dirname,"./public")))​//路由級别的中間件app.use("/user",indexRouter)​app.listen(9000,()=>{

5、第三方中間件

例如 cheerio jsonwebToken等

6、自定義中間件

自己根據需求封裝的中間件