node

官網

https://nodejs.org/en/html

nodeJs搭建一個簡單的服務器

瀏覽器和服務器通訊須要http協議完成node

    //1 引入http模塊
    var http = require('http');
    //2 建立服務器                           請求      響應
    var server = http.createServer(function(request,response){
        console.log('有訪問');
        response.write('abc');
        response.end();
    })
    //3 監聽8080端口
    server.listen(8080);
    //4 終端輸入 node server.js啓動服務器
    //5 瀏覽器測試 localhost:8080 頁面雖然無顯示,可是控制檯中每當有訪問會打印 有訪問

response 響應給客戶端的信息

1 response.write() 會輸出到瀏覽器
2 response.end() 輸出結束

request 請求過來的信息 01/request.js

1 request.url 請求過來的url
    localhost:8080/1.html
    /1.html
    /favicon.ico  瀏覽器自動給你請求的網站小圖標

fs 模塊

  • 問題一:頁面多了,不可能都寫在switch case中
  • 問題二:只能響應文字類的東西,沒法返回文件
  • 問題三:每次修改都要從新啓動服務器

1 readFile(文件名,回調) 02fs/1.js

        fs.readFile('aaa.txt',function(err,data){
            console.log(data);
            //<Buffer 73 66 61 73 6b 6c 66 6a 0a 31 31 31 31 0a 32 32 32 32 0a 33 33 33 33 0a>
            console.log(data.toString());//把二進制轉爲 字符串
        })

2 writeFile(文件名,內容,回調) 02fs/1.js

        fs.writeFile('bbb.txt','new data',function(err,data){
            console.log(err,'err');
            console.log(data,'data');
        })

fs與服務器結合 02fs/server.js

1 02fs/www 網站根目錄,能夠外部訪問的根目錄

        req.url => '/index.html'
        讀取 './www/index.html'
        './www'+req.url

        var fileName = './www'+req.url;

2 www/index.html

        <div style="background:red;">
          div
        </div>

3 02fs/server.js

        const http = require('http');
        const fs = require('fs');

        var server = http.createServer(function(req,res){
            var filename = './www' + req.url;
            fs.readFile(filename,(err,data)=>{
                if(err){
                    res.write('404');
                }else{
                    res.write(data);//機器對機器原本就是二進制,因此不用toString
                }
                res.end();
            })
        })

        server.listen(8080);

4 當前服務器問題,須要可以接收到前臺發過來的參數

http-解析get參數 03get/server.js 03get/form.html

接收前臺的數據請求mysql

  • 前臺: form、ajax、jsonp
  • 後臺: 同樣
  • 前臺《---》 後臺 :走的都是http協議,對後臺而言只是接收到一個http請求

請求方式不一樣,接收不一樣

1 GET:數據在url中
2 POST:數據不在url中
    請求頭 header

    請求體 content  POST數據

queryString 解析查詢字符串 03get/queryString.js

    const queryString = require('queryString');
    var json = queryString.parse("username=yuonly&password=123123");
    console.log(json);

url模塊 方便的獲取地址和get數據 03get/url.js

        const urlLib = require('url');
        //沒有第二個參數時
        var obj = urlLib.parse('http://www.zyx58.com/index?a=12&b=5');

        console.log(obj);
        //obj 結果
        Url {
          protocol: 'http:', 協議
          slashes: true,
          auth: null,
          host: 'www.zyx58.com', 主機
          port: null, 端口
          hostname: 'www.zyx58.com', 主機名
          hash: null,
          search: '?a=12&b=5',
          query: 'a=12&b=5',數據
          pathname: '/index',地址
          path: '/index?a=12&b=5',請求路徑
          href: 'http://www.zyx58.com/index?a=12&b=5'
        }

        //第二個參數爲true時

        var obj = urlLib.parse('http://www.zyx58.com/index?a=12&b=5',true);

        console.log(obj);

        Url {
          protocol: 'http:',
          slashes: true,
          auth: null,
          host: 'www.zyx58.com',
          port: null,
          hostname: 'www.zyx58.com',
          hash: null,
          search: '?a=12&b=5',
          query: { a: '12', b: '5' }, 數據 query已經被解析爲json
          pathname: '/index', //地址
          path: '/index?a=12&b=5',
          href: 'http://www.zyx58.com/index?a=12&b=5'
        }

使用url搭建server 來解析請求地址和get參數 03get/urlServer.js

        const http = require('http');

        const urlLib = require('url');

        http.createServer((req,res)=>{
            var obj = urlLib.parse(req.url,true);
            var url = obj.pathname;
            var GET = obj.query;
            console.log(url,GET);
        }).listen(8080);

總結:get參數獲取方式 最大 32K

  • 本身動手用 split切
  • queryString 模塊
  • url 模塊

POST數據獲取方式 1G 04post/server.js 04post/form.html

1 on('data',function(data){}) 每當有一段數據到達的時候,就會觸發一次
2 on('end',function(){}) 數據徹底到達的時候觸發一次
3 數據解析仍然可使用 queryString模塊解析
        var http = require('http');
        var queryString = require('queryString');

        http.createServer((req,res)=>{
            //post - req post 數據大,因此要分段發送
            //data 每當有一段數據到達的時候,就會觸發一次
            //end 數據徹底到達的時候觸發一次
            var str = '';//等待接收數據
            var i = 0;//驗證是否分不少次到達
            req.on('data',function(data){
                console.log(`第${i++}次到達`);
                str += data;
            })
            req.on('end',function(){
                // console.log(str);
                var POST = queryString.parse(str);
                console.log(POST);
            })
        }).listen(8080);

server基本內容 05base_server/server.js

        const http = require('http');

        const fs = require('fs');

        const queryString = require('queryString');

        const urlLib = require('url');

        http.createServer((req,res)=>{
            //GET
            var obj = urlLib.parse(req.url,true);
            var url = obj.pathname;
            const GET = obj.query;
            //POST
            var str = '';
            var POST = {};
            req.on('data',function(data){
                str += data;
            })
            req.on('end',function(){

                POST = queryString.parse(str);
                console.log(url,GET,POST);
            })
            // url  要那個文件
            // GET  get數據
            // POST post數據

        // ================ 文件請求======
            var filename = './www'+url;
            fs.readFile(filename,function(err,data){
                if(err){
                    res.write('404');
                }else{
                    res.write(data);
                }
                res.end();
            })

            // localhost:8080/aaa.html


        }).listen(8080);

httpserver 實現用戶註冊/登陸 06httpserver

1 接口

  • 註冊:/user?act=reg&username=aaa&pwd=123 return {"ok":false,"msg":"緣由"} {"ok":true,"msg":"成功信息"}
  • 登陸: /user?act=login&username=aaa&pwd=123

2 對接口的訪問 if(url=='/user')

3 對文件的訪問 else


模塊化 07module

文檔 : http://nodejs.cn/api/git

  • 系統模塊: http、queryString、url、Crypto-加密、Events-事件、Net-網絡操做、OS-操做系統信息、Path-處理文件路徑、Stream-流操做、Timer-定時器(interval/timeout)、SSL-加密傳輸、utils-工具方法、ZLIB-壓縮
  • 自定義模塊:
  • 模塊管理:包管理器

自定義模塊

  • 模塊組成
  • npm
  • 發佈本身的模塊

1 模塊組成

  • require: 引入模塊ajax

    既能夠引入系統模塊,又能夠引入文件模塊,因此即使是當前目錄也要加上 ./
    
    沒有全局變量,至關於
    (function(require,exports,module){
        var a = 12;
        exports.a = 12;
    })()
    
  • exports: 導出、輸出。一個一個輸出sql

  • module: 模塊。批量輸出東西npm

    對外輸出一堆東西
    exports.a = 12;
    exports.b = 5;
    exports.c = 99;
    
    module.exports = {a:12,b:5,c:99}
    
    console.log(module.exports === exports);//true:說明是一個東西
    

require('./mod1.js') .js能夠省略不寫json

npm:Nodejs Package Manager(Nodejs包管理器)

  • 統一的下載途徑。相似360軟件管家
  • 自動下載依賴api

        安裝
        npm i mysql --save
        卸載
        npm uninstall mysql
    

npm

1 手動建立node_modules目錄
2 把 mod1.js放入 node_modules目錄中
3 require('mod1.js'); 能夠不加./了

require 1. 若是有 './' 從當前目錄找瀏覽器

  1. 若是沒有 ‘./’。首先從系統模塊中找,沒有,再去node_modules目錄中找

發佈本身的模塊

1 註冊帳號
2 登陸
    npm login
    輸入用戶名、密碼、郵箱
3 查看當前登陸的帳號
    npm whoami
4 npm init初始化包信息,會生成package.json
5 發佈
    npm publish
6 更新
    npm update test0528
7 刪除
    npm unpublish --force
相關文章
相關標籤/搜索