node.js學(xué)習(xí)筆記之koa框架和簡單爬蟲練習(xí)
Koa -- 基于 Node.js 平臺的下一代 web 開發(fā)框架
koa是由 Express 原班人馬打造的,致力于成為一個更小、更富有表現(xiàn)力、更健壯的 Web 框架。 使用 koa 編寫 web 應(yīng)用,可以免除重復(fù)繁瑣的回調(diào)函數(shù)嵌套, 并極大地提升錯誤處理的效率。koa 不在內(nèi)核方法中綁定任何中間件, 它僅僅提供了一個輕量優(yōu)雅的函數(shù)庫,使得編寫 Web 應(yīng)用變得得心應(yīng)手。開發(fā)思路和express差不多,最大的特點(diǎn)就是可以避免異步嵌套。koa2利用ES7的async/await特性,極大的解決了我們在做nodejs開發(fā)的時候異步給我們帶來的煩惱。
英文官網(wǎng):http://koajs.com
中文官網(wǎng):http://koajs.cn
1.koa
安裝koa包: npm i -S koa@latest
引入: const koa = require("koa");
實例化對象: const app = new koa;
通過實例操作,專門用于客戶端請求的函數(shù)叫做中間件,使用use()注冊
use()函數(shù)中必須使用異步 async; use可是調(diào)用無數(shù)次;
其中有兩個參數(shù):
a)ctx: 上下文環(huán)境,node的請求和響應(yīng)對象,其中不建議使用node原生的req和res屬性,使用koa封裝的requset和response屬性
b)next: next(),將本次控制權(quán)交給下一個中間件。
最后一個中間件使用next()無意義,執(zhí)行完控制權(quán)返回上一層,直至第一個。
1. next參數(shù)的使用demo
const Koa = require("koa"); const koa = new Koa(); //中間件1 koa.use(async (ctx, next) => { console.log("1 , 接收請求控制權(quán)"); await next(); //將控制權(quán)傳給下一個中間件 console.log("1 , 返回請求控制權(quán)"); }); //將中間件注冊到koa的實例上 //中間件2 koa.use(async (ctx, next) => { console.log("2 , 接收請求控制權(quán)"); await next(); console.log("2 , 返回請求控制權(quán)"); }); //中間件3 koa.use(async (ctx, next) => { console.log("3 , 接收請求控制權(quán)"); console.log("3 ,返回請求控制權(quán)"); }); koa.listen(3000, ()=>{ console.log("開始監(jiān)聽3000端口"); });
注:當(dāng)中間件中沒有next(),不會執(zhí)行下面的中間件
訪問localhost:3000的效果圖;
注:會有兩次操作是因為圖標(biāo)icon也會請求一次
2.ctx參數(shù)的使用demo
const Koa = require("koa"); const koa = new Koa(); koa.use(async (ctx, next)=>{ ctx.body = "body可以返回數(shù)據(jù),"; ctx.body += "可以多次調(diào)用,"; ctx.body += "不需要end()"; }); koa.listen(3000, ()=>{ console.log("監(jiān)聽開始"); });
效果:
ctx.url ,ctx.path ,ctx.query ,ctx.querystring ,ctx.state ,ctx.type
const Koa = require("koa"); const koa = new Koa(); koa.use(async (ctx, next)=>{ ctx.body = ctx.url; ctx.body = ctx.path; ctx.body = ctx.query; ctx.body = ctx.querystring; }); koa.listen(3000, ()=>{ console.log("監(jiān)聽開始"); });
訪問http://localhost:3000/path?name=sjl&age=18為例,效果圖:
1. url: 整個路徑
2. path: 非查詢部分
3. query: 將查詢部分轉(zhuǎn)為JSON對象
4. querystring: 將查詢部分轉(zhuǎn)為字符串
5. ctx.state ,ctx.type 表示狀態(tài)嗎和類型
2.簡單爬蟲練習(xí)
安裝request,cheerio模塊
npm i -S request: 請求模塊 npm i -S cheerio: 抓取頁面模塊(JQ核心)
抓取網(wǎng)頁數(shù)據(jù)案例(隨機(jī)網(wǎng)頁)
//導(dǎo)入模塊 const request = require("superagent"); //導(dǎo)入請求模塊 const cheerio = require("cheerio"); const {join} = require("path"); const fs = require("fs"); let arr = [], //存放數(shù)據(jù) reg = /\n|\s+/g, //replace中使用 url = "https://www.shiguangkey.com/course/search?key=%E5%89%8D%E7%AB%AF/"; request .get(url) .end((err, res) => { const $ = cheerio.load(res.text); //把字符串內(nèi)的標(biāo)簽當(dāng)成dom來使用 $(".course-item").each((i, v) => { // v當(dāng)前進(jìn)來的dom,根據(jù)網(wǎng)頁的布局結(jié)構(gòu)來找到準(zhǔn)確的dom節(jié)點(diǎn) const obj = { imgSrc : $(v).find("img").prop("src"), price : $(v).find(".fr span").text().replace(reg, ""), total : $(v).find(".item-txt").text().replace(reg, ""), href : join(url + $(v).find(".cimg").prop("href")) }; console.log(join(url + $(v).find(".cimg").prop("href"))); //拼接 arr.push(obj); //把對象放進(jìn)數(shù)組里 }); fs.writeFile("./sjl.json", JSON.stringify(arr)); //將爬到的數(shù)據(jù)寫入文檔中 });
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Nodejs-child_process模塊詳細(xì)介紹
Node.js的child進(jìn)程模塊允許創(chuàng)建并行任務(wù),提高應(yīng)用性能,介紹了exec、execFile、spawn、fork等方法,解釋了它們的使用場景和優(yōu)勢,通過子進(jìn)程模塊,可以執(zhí)行外部命令、腳本或創(chuàng)建新的Node.js實例,感興趣的朋友跟隨小編一起看看吧2024-09-09npm?install安裝失敗報錯:The?operation?was?rejected?by?your?
這篇文章主要給大家介紹了關(guān)于npm?install安裝失敗報錯:The?operation?was?rejected?by?your?operating?system的相關(guān)資料,文中給出了多種解決方法供大家參考學(xué)習(xí),需要的朋友可以參考下2023-04-04