為了學習egg框架是如何接受常見的http請求,以及如何返回數據,我特意寫了個form的demo
<!-- view/hello.ejs --> <form action="/form" method="post"> <input type="text" name="name" placeholder="name"> <input type="text" name="age" placeholder="age"> <input type="submit" value="提交"> </form>
// router.js
'use strict';
module.exports = app => {
app.get('/', 'render.ejs');
app.post('/form',app.controller.form.listPosts)
};
// controller/form.js
const Controller = require('egg').Controller; module.exports = class PostController extends Controller { * listPosts() { this.ctx.body = { name: this.ctx.request.body.name, age: this.ctx.request.body.age } } };
<h3>name: <%=name%></h3> <h3>age: <%= age %></h3>
然后我就直接開始試驗了,結果一直報錯,403,說是什么安全驗證什么鬼的,后面我詳細去看官方文檔,看到了這樣一句話
附:
這里直接發起 POST 請求會報錯:'secret is missing'。錯誤信息來自 koa-csrf/index.js#L69 。
后面詳細的看完才知道,原來是egg框架的這個內置安全插件搞的鬼。簡單的說吧,這個插件的功能就是在你每次post請求進來的時候,會先檢查你 請求自帶的參數里面帶不帶一個特定的參數,這個參數就相當於一個秘鑰,它存在於你請求的cookie中,你請求的時候需要帶上一個特定參數名,並且參數值等於這個秘鑰的數據,也可以直接放在請求頭header里面,看文檔去設置就好。
再說明白一點,你請求的時候,服務器會問你“天王蓋地虎”,你必須回答“小雞燉蘑菇”,一個道理,只不過這個 “小雞燉蘑菇” 口令是存在於你請求的cookie里面的,你需要做的就是從cookie中拿出來,然后放到header里面或者直接加到你請求的參數里面 https://eggjs.org/zh-cn/core/security.html#安全威脅-csrf-的防范
總的來說,個人感覺阿里的這個框架還是非常牛逼的,至少安全方面做得非常好,值得去深入的學習一下。