1. 抽取函數處理
-
引入模塊
-
http協議和https協議兩種,既有不同,那麼模塊引入創建的變量自然不同
-
url對象的
parse
方法能獲得http
或者https
協議的信息。以http://example.com:8080/one?a
爲例打印。{ protocol : 'http:' , auth : null , host : 'example.com:8080' , port : '8080' , hostname : 'example.com' , hash : null , search : '?a=index&t=article&m=default', query : 'a=index&t=article&m=default', pathname : '/one', path : '/one?a=index&t=article&m=default', href : 'http://example.com:8080/one?a=index&t=article&m=default' }
-
protocol
屬性保存了協議if(urlObj.protocol == 'http:'){ http = require('http'); } else{ http = require('https'); }
-
處理
error
頁面req.on('error',()=>{ console.log('404'); })
####### 完整代碼
const fs = require('fs'); const url = require('url') GetUrl('https://detail.tmall.com/item.htm?spm=a230r.1.14.6.68624507tWuF7E&id=560257961625&cm_id=140105335569ed55e27b&abbucket=18&sku_properties=10004:709990523',data=>{ fs.writeFile('iponex.html',data); }) function GetUrl(sUrl,success){ var urlObj = url.parse(sUrl); var http =''; if(urlObj.protocol == 'http:'){ http = require('http'); } else{ http = require('https'); } let req = http.request({ 'hostname':urlObj.hostname, 'path':urlObj.path },res=>{ console.log(res) var arr = []; res.on('data',buffer=>{ arr.push(buffer); }); res.on('end',()=>{ let b = Buffer.concat(arr); success && success(b); }) }); req.end(); req.on('error',()=>{ console.log('404'); }) }