node學習(1) -- HTTP模塊/URL模塊

(一) 運行服務

首先我們先來學習一種最簡單的用命令行跑node代碼的方式:
到當前node代碼所處文件下,假設我們的代碼在study.js中,則運行node study.js即可;

這裏寫圖片描述

可是上述方法有一個特別不好的地方, 就是每一次我們修改之後都要重新執行一下。

接下來就來介紹一個自啓動工具supervisor,有了他就能實時的監聽頁面變化
使用也很簡單:全局安裝該工具

npm install -g supervisor

然後將我們之前執行的 node 替換成 supervisor 就可以了

(二) http模塊

// 引用http模塊
var http = require('http');

// 創建一個服務
var server = http.createServer(function(req,res){
    // req 表示請求的內容 ; res 表示響應的內容
    res.writeHead(200, {"Content-Type": "text/html;charset=UTF8"}); // 設置響應頭
    res.write('響應的內容');
    res.end(); // 此方法使web服務器停止處理腳本並返回當前結果
});

server.listen(3000); // 監聽3000端口

這裏寫圖片描述

(三) url模塊

url模塊主要是用來處理用戶請求的url地址,即req.url

我們主要了解下url的幾個方法:

  1. url.parse() 解析url

(1) 不帶查詢字符串的情況

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com',
  port: null,
  hostname: 'www.baidu.com',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'http://www.baidu.com/' }

(2)帶查詢字符串的情況 , 可以在search / query處拿到

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com',
  port: null,
  hostname: 'www.baidu.com',
  hash: null,
  search: '?username=test&password=123',
  query: 'username=test&password=123',
  pathname: '/',
  path: '/?username=test&password=123',
  href: 'http://www.baidu.com/?username=test&password=123' }

(3)第二個參數設置爲true, 默認爲false,
將query中的查詢字符串轉化成對象格式

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com',
  port: null,
  hostname: 'www.baidu.com',
  hash: null,
  search: '?username=test&password=123',
  query: { username: 'test', password: '123' },
  pathname: '/',
  path: '/?username=test&password=123',
  href: 'http://www.baidu.com/?username=test&password=123' }

(4) 第三個參數設置爲true , 默認爲false

// 這種是默認情況下應該顯示的, 此時第三個參數就是默認的false 
// 這種情況下//後面的內容都會被歸屬到pathname中
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: null,
  query: null,
  pathname: '//foo/test',
  path: '//foo/test',
  href: '//foo/test' }

// 下面這種情況就是我們手動的將第三個參數設置爲true
// 這種情況下 會將 //到下一個/之間的內容作爲host,/後面的內容作爲pathname
Url {
  protocol: null,
  slashes: true,
  auth: null,
  host: 'foo',
  port: null,
  hostname: 'foo',
  hash: null,
  search: '',
  query: {},
  pathname: '/test',
  path: '/test',
  href: '//foo/test' }
  1. url.format url.parse的逆向操作
var urlParse = url.parse('http://www.baidu.com');
var urlformat = url.format(urlParse); // http://www.baidu.com
  1. url.resolve(from, to) 添加或者替換地址
    from : 解析時相對的基本url
    to: 要解析的超鏈接url
url.resolve('/one/two/three', 'four') // '/one/two/four'
url.resolve('http://www.baidu.com/', 'four') // 'http://www.baidu.com/four'
url.resolve('http://www.baidu.com/three', 'four') // 'http://www.baidu.com/four'
發佈了95 篇原創文章 · 獲贊 137 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章