npm i -S koa@latest
const koa = require("koa");
const app = new koa;
經過實例操做,專門用於客戶端請求的函數叫作中間件,使用use()註冊node
use()函數中必須使用異步 async; use但是調用無數次;
其中有兩個參數:
a)ctx: 上下文環境,node的請求和響應對象,其中不建議使用node原生的req和res屬性,使用koa封裝的requset和response屬性
b)next: next(),將本次控制權交給下一個中間件。
最後一箇中間件使用next()無心義,執行完控制權返回上一層,直至第一個。npm
const Koa = require("koa");
const koa = new Koa();
//中間件1
koa.use(async (ctx, next) => {
console.log("1 , 接收請求控制權");
await next(); //將控制權傳給下一個中間件
console.log("1 , 返回請求控制權");
}); //將中間件註冊到koa的實例上
//中間件2
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(),不會執行下面的中間件json
訪問localhost:3000的效果圖;數組
注:會有兩次操做是由於圖標icon也會請求一次bash
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("監聽開始");
});
複製代碼
效果: app
ctx.url ,ctx.path ,ctx.query ,ctx.querystring ,ctx.state ,ctx.typedom
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爲例,效果圖:koa
安裝request,cheerio模塊異步
npm i -S request: 請求模塊
npm i -S cheerio: 抓取頁面模塊(JQ核心)
複製代碼
抓取網頁數據案例(隨機網頁)async
//導入模塊
const request = require("superagent"); //導入請求模塊
const cheerio = require("cheerio");
const {join} = require("path");
const fs = require("fs");
let arr = [], //存放數據
reg = /\n|\s+/g, //replace中使用
url = "";
request
.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)); //將爬到的數據寫入文檔中
});
複製代碼