node.js學習筆記之koa框架和簡單爬蟲練習

Koa -- 基於 Node.js 平臺的下一代 web 開發框架前端

koa是由 Express 原班人馬打造的,致力於成爲一個更小、更富有表現力、更健壯的 Web 框架。 使用 koa 編寫 web 應用,能夠免除重複繁瑣的回調函數嵌套, 並極大地提高錯誤處理的效率。koa 不在內核方法中綁定任何中間件, 它僅僅提供了一個輕量優雅的函數庫,使得編寫 Web 應用變得駕輕就熟。開發思路和express差很少,最大的特色就是能夠避免異步嵌套。koa2利用ES7的async/await特性,極大的解決了咱們在作nodejs開發的時候異步給咱們帶來的煩惱。node

英文官網:koajs.comweb

中文官網:koajs.cnexpress

1.koanpm

安裝koa包: npm i -S koa@latest
引入: const koa = require("koa");
實例化對象: const app = new koa;json

經過實例操做,專門用於客戶端請求的函數叫作中間件,使用use()註冊數組

use()函數中必須使用異步 async; use但是調用無數次;bash

其中有兩個參數:app

a)ctx: 上下文環境,node的請求和響應對象,其中不建議使用node原生的req和res屬性,使用koa封裝的requset和response屬性框架

b)next: next(),將本次控制權交給下一個中間件。

最後一箇中間件使用next()無心義,執行完控制權返回上一層,直至第一個。

1. next參數的使用demo

`const Koa = require(``"koa"``);`
`const koa =` `new` `Koa();`
`//中間件1`
`koa.use(async (ctx, next) => {`
`console.log(``"1 , 接收請求控制權"``);`
`await next();` `//將控制權傳給下一個中間件`
`console.log(``"1 , 返回請求控制權"``);`
`});` `//將中間件註冊到koa的實例上`
`//中間件2`
歡迎加入全棧開發交流划水交流圈:582735936
面向划水1-3年前端人員
幫助突破划水瓶頸,提高思惟能力
`koa.use(async (ctx, next) => {`
`console.log(``"2 , 接收請求控制權"``);`
await next();`
`console.log(``"2 , 返回請求控制權"``);`
`});`
`//中間件3`
`koa.use(async (ctx, next) => {`
`console.log(``"3 , 接收請求控制權"``);`
`console.log(``"3 ,返回請求控制權"``);`
`});`
`koa.listen(3000, ()=>{`
`console.log(``"開始監聽3000端口"``);`
`});`
複製代碼

注:當中間件中沒有next(),不會執行下面的中間件

訪問localhost:3000的效果圖;


注:會有兩次操做是由於圖標icon也會請求一次

2.ctx參數的使用demo

`const Koa = require(``"koa"``);`
`const koa =` `new` `Koa();`
`koa.use(async (ctx, next)=>{`
`ctx.body =` `"body能夠返回數據,"``;`
`ctx.body +=` `"能夠屢次調用,"``;`
`ctx.body +=` `"不須要end()"``;`
`});`
`koa.listen(3000, ()=>{`
`console.log(``"監聽開始"``);`
`});`
複製代碼

效果:


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(``"監聽開始"``);`
`});`
複製代碼

訪問http://localhost:3000/path?name=sjl&age=18爲例,效果圖:

1. url: 整個路徑


2. path: 非查詢部分


3. query: 將查詢部分轉爲JSON對象


4. querystring: 將查詢部分轉爲字符串


5. ctx.state ,ctx.type 表示狀態嗎和類型

2.簡單爬蟲練習

安裝request,cheerio模塊

`npm i -S request: 請求模塊`
`npm i -S cheerio: 抓取頁面模塊(JQ核心)`
複製代碼

抓取網頁數據案例(隨機網頁)

`//導入模塊`
`const request = require(``"superagent"``);` `//導入請求模塊`
`const cheerio = require(``"cheerio"``);`
`const {join} = require(``"path"``);`
`const fs = require(``"fs"``);`
`let arr = [],` `//存放數據`
`reg = /\n|\s+/g,` `//replace中使用`
`url =` `"[https://www.shiguangkey.com/course/search?key=%E5%89%8D%E7%AB%AF/](https://www.shiguangkey.com/course/search?key=%E5%89%8D%E7%AB%AF/)"``;`
`request`
歡迎加入全棧開發交流划水交流圈:582735936
面向划水1-3年前端人員
幫助突破划水瓶頸,提高思惟能力
`.get(url)`
`.end((err, res) => {`
`const $ = cheerio.load(res.text);` `//把字符串內的標籤當成dom來使用`
`$(``".course-item"``).each((i, v) => {`
`// v當前進來的dom,根據網頁的佈局結構來找到準確的dom節點`
`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);` `//把對象放進數組裏`
`});`
`fs.writeFile(``"./sjl.json"``, JSON.stringify(arr));` `//將爬到的數據寫入文檔中`
`});`
複製代碼

以上就是本文的所有內容,但願對你們的學習有所幫助

相關文章
相關標籤/搜索