## 使用中間件設置全局變量
## 1.設置中間件,配置全局變量
~~~
//middleware/auth.js
module.exports = (option,app)=>{
return async function auth(ctx,next){
/* 設置模板的全局變量 */
ctx.state.csrf = ctx.csrf;
await next();
}
}
~~~
## 2.在模板中使用
~~~
<form action="/add?_csrf=<%= csrf%>" method='post'>
<p>用戶名: <input type="text" name="username"></p>
<p>密碼: <input type="password" name="password"></p>
<input type="submit" value="提交">
</form>
~~~
模板的另一中傳遞csrf的方式
~~~
<form action="/add" method='post'>
<input type = "hidden" name="_csrf" value="<%= csrf%>"/>
<p>用戶名: <input type="text" name="username"></p>
<p>密碼: <input type="password" name="password"></p>
<input type="submit" value="提交">
</form>
~~~