在完成了爬取數(shù)據(jù)的借口之后名段,遇到了一些問題:
- 接口沒有做保護(hù),可能會(huì)被人惡意一直請(qǐng)求,導(dǎo)致一直爬取數(shù)據(jù)導(dǎo)致內(nèi)存溢出
使用表單提交的方式
- 只有在密碼輸入正確的前提下豪娜,才可以成功請(qǐng)求。
定義表單
router.get('/',(req:Request,res:Response)=>{
const formHtml = `
<body>
<form method='POST' action='/getData'>
<input type='password' name='password'>
<button>Submit</button>
</form>
</body>
`
res.send(formHtml)
})
但在提交了之后哟楷,缺拋出這樣的錯(cuò):
image.png
原因是雖然數(shù)據(jù)已經(jīng)在request.body里了瘤载,但express并沒有對(duì)其進(jìn)行有效地解析。
借助body-parser
這個(gè)中間件幫忙進(jìn)行解析:
安裝:npm install body-parser
表單提交使用:app.use(bodyParser.urlencoded({ extended: false }))
配置了之后就可以了卖擅。
但引入了兩個(gè)ts下的express問題:
-
為什么body.password是undefined, ts卻沒有拋出任何的錯(cuò)
原因:在express的類型注解文件中鸣奔,Response是any
image.png - 對(duì)req的改變只是改變了值,并沒有改變其對(duì)應(yīng)的類型惩阶。
為了解決上述的兩個(gè)問題挎狸,需要對(duì)express的類型描述文件進(jìn)行擴(kuò)展
對(duì)express的類型描述文件進(jìn)行拓展
- 補(bǔ)充定義
//對(duì)body下的屬性進(jìn)行拓展
interface RequestWithForm extends Request{
body:{
password:string | undefined
//[key:string]:string || undefined
}
}
2.增加描述文件來拓展類型
可以借鑒import * as core from "express-serve-static-core";
這一個(gè)文件
declare namespace Express {
// These open interfaces may be extended in an application-specific manner via declaration merging.
// See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts)
interface Request {
username:string
}
interface Response { }
interface Application { }
}
ts的特性,可以使用類型融合對(duì)request断楷,response進(jìn)行拓展锨匆。