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)
next()})​app.use((req,res,next)=>{
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,()=>{
console.log("server address:127.0.0.1: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,()=>{
console.log("server address:127.0.0.1:9000")})

5、第三方中間件
例如 cheerio jsonwebToken等

6、自定義中間件
自己根據需求封裝的中間件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章