日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

koa --- seesion实现登录鉴权

發(fā)布時(shí)間:2023/12/10 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 koa --- seesion实现登录鉴权 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

koa + vue + session 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的登錄邏輯

  • /login component/login-session.html
<!DOCTYPE html><head><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head><body><div id="app"><div><input v-model="username" /><input v-model="password" /></div><div><button @click="login">Login</button><button @click="logout">Logout</button><button @click="getUser">GetUser</button></div><div><button @click="logs=[]">Clear Log</button></div><!-- 日志 --><ul><li v-for="(log, idx) in logs" :key="idx">{{log}}</li></ul></div><script>// 這行代碼很關(guān)鍵,請(qǐng)求時(shí)攜帶cookieaxios.defaults.withCredentials = true;axios.interceptors.response.use(response => {app.logs.push(JSON.stringify(response.data));return response;});var app = new Vue({el: '#app',data: {username: "test",password: "test",logs: []},methods: {login: async function() {await axios.post("http://localhost:3000/users/login", JSON.stringify({username: this.username,password: this.password}))},logout: async function() {await axios.post("http://localhost:3000/users/logout", JSON.stringify({username: this.username}))},getUser: async function() {await axios.get("http://localhost:3000/users/getUser");}}});</script> </body></html>
  • 注:
  • axios.defaults.withCredentials = true: 前端發(fā)出請(qǐng)求時(shí),攜帶 cookie
  • axios.post(url,params)時(shí),params 一定要使用 JSON.stringify 轉(zhuǎn)換成 JSON 格式.否則會(huì)出現(xiàn)請(qǐng)求方法為 OPTION.
  • axios.interceptors.response.use(cb): 對(duì)響應(yīng)的信息進(jìn)行攔截處理.
    • 下面搭一個(gè)最基礎(chǔ)的后端.
    const Koa = require('koa') const app = new Koa()// 路由 const Router = require('koa-router') const router = new Router({ prefix: '/users' })router.post('/login', async ctx => {ctx.body = {ok: 1,message: '登錄成功'} })router.post('/logout', async ctx => {ctx.body = {ok: 1,message: '登出成功'} })router.post('/getUser', async ctx => {ctx.body = {ok: 1,message: '獲取用戶成功'} })app.use(router.routes()) app.listen(3000)
    • 說(shuō)明:
  • const router = new Router({ prefix: '/users' }): 給路由添加一個(gè)前綴,即在后面 router.post(’/’,cb), 處理的是 http://localhost:3000/users 路由
  • 以上的 html 是運(yùn)行在 file 協(xié)議下(vscode 下使用 alt + B 快捷打開(kāi)),而服務(wù)端是 http 協(xié)議.當(dāng) html 上通過(guò) axios.post 方法請(qǐng)求服務(wù)器時(shí),會(huì)發(fā)生跨域.于是下面需要添加跨域
  • 由于使用到了 POST 方法,因此,在服務(wù)端也添加上 bodyParser.(注: bodyParser 一定要放在 koa-router 前面加載)
  • // post 請(qǐng)求解析 const bodyParser = require('koa-bodyparser') app.use(bodyParser())// 跨域 const cors = require('koa2-cors') app.use(cors())
    • 說(shuō)明:
  • 如果您按照我的代碼一步一步的敲,那么當(dāng)您敲到這里,代碼應(yīng)該理所當(dāng)然的不能運(yùn)行.打開(kāi) google 瀏覽器,在控制臺(tái)可以看見(jiàn)以下的一段話
  • The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.:提示的很明顯,就是說(shuō)需要在返回頭部加上一個(gè) “Access-Control-Allow-Credentials”: true 字段
  • 根據(jù) koa2 的洋蔥模型,只需在所有的路由前面加上如下代碼即可
  • router.post('*', async (ctx, next) => {ctx.set('Access-Control-Allow-Credentials', true)await next() }) router.get('*', async (ctx, next) => {ctx.set('Access-Control-Allow-Credentials', true)await next() })
    • 說(shuō)明:
  • 如果您按照我的代碼一步一步的敲,那么當(dāng)您敲到這里基本的前后端交互算是完成了,下一步需要使用 session
  • 首先看如下代碼:
  • // session(配置) const session = require('koa-session') app.kets = ['marron rain']const SESSION_CONFIG = {key: 'marron:session' } app.use(session(SESSION_CONFIG, app))// session(使用) // 改寫(xiě)login router.post('/login', async ctx => {// 登錄邏輯ctx.session.userinfo = "marron";ctx.set("Content-Type", "application/json");ctx.body = {ok: 1,message: '登錄成功',} }) router.post('/logout', async ctx => {delete ctx.session.userinfo;ctx.body = {ok: 1,message: '退出系統(tǒng)'}})router.get('/getUser', async ctx => {ctx.body = {ok: 1,message: '獲取用戶成功',userinfo: ctx.session.userinfo} })
    • 說(shuō)明:
  • 此時(shí),后端可以處理 登錄、登出、以及獲取信息.(僅僅只是根據(jù)不同路由返回不同的信息,并未進(jìn)行邏輯處理)
  • 實(shí)現(xiàn)簡(jiǎn)單的邏輯
    • 在處理 getUser 路由請(qǐng)求時(shí),先檢查一下session中是否有信息
    • 使用router.post 的第二個(gè)參數(shù), 傳入中間件.
    • /login component/middleware/auth.js
    module.exports = async (ctx, next) =>{if(!ctx.session.userinfo) {ctx.body = {ok: 0,message: '用戶未登錄'}} else {await next();} }
    • 將router.get('/getUser')改寫(xiě)如下:
    router.get('/getUser', require('./middleware/auth'), async ctx =>{ctx.body = {ok: 1,message: '獲取用戶成功',userinfo: ctx.session.userinfo} })
    • 說(shuō)明:
  • 在執(zhí)行回調(diào)函數(shù)之前,會(huì)先執(zhí)行監(jiān)測(cè),檢查session中是否存在userinfo信息.
  • 邏輯基本完成.但是此時(shí)的session信息只是存在內(nèi)存中,并未真正實(shí)現(xiàn)持久化.
  • 總結(jié)

    以上是生活随笔為你收集整理的koa --- seesion实现登录鉴权的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。