search
HomeWeb Front-endJS TutorialHow to operate nuxt framework for routing authentication and use Koa and Session

This time I will show you how to operate the nuxt framework for routing authentication and use Koa and Session, how to operate the nuxt framework for routing authentication and use Koa and SessionNotes What are they? Here are actual cases. Let’s take a look.

Introduction

The backend management page of the blog requires a login system, so consider doing routing authentication. The implementation method is also given by the Nuxt official website. Chestnut was rewritten, and the front-end and back-end routing were also unified.

Route interception

The front-end mainly uses Nuxt’s middleware to do route interception. Vuex is also required here. State tree is used to do it.

middleware

middleware/auth.js

export default function ({ store, redirect }) {
 
 if (!store.state.user) {
  return redirect('/login')
 }
}

Re-authenticate the page by verifying whether the user information on the status tree exists. Orientation

layouts/admin.vue

export default {
  middleware: 'auth',
  components: {
   AdminAside
  }
 }

Add middleware on the page layout of the background management system

nuxtServerInit

In the rendering process of NuxtJs, when a request comes in, the nuxtServerInit method is called first. This method can be used to save the server's data in advance.

We can use this method to receive Session information that stores user information.

nuxtServerInit ({ commit }, { req, res }) {
  if (req.session && req.session.user) {
   const { username, password } = req.session.user
   const user = {
    username,
    password
   }
   commit('SET_USER', user)
  }
 },

When the application is completed, some data we obtained from the server will be filled in this state tree (store).

According to the examples given on the NuxtJs official website, we have basically finished writing the routing authentication part of the page. The next step is to write the code for this part of the server side

Using Koa and koa-session

Koa and koa-session

The back-end code I use is the Koa framework, and koa- session to process the Session.

When creating a new nuxt project, you can directly choose the Koa framework.

vue init nuxt/koa

Related dependencies

npm install koa-session

Rewrite in server.js

import Koa from 'koa'
import { Nuxt, Builder } from 'nuxt'
// after end
import session from 'koa-session'
async function start () {
 const app = new Koa()
 const host = process.env.HOST || '127.0.0.1'
 const port = process.env.PORT || 7998
 // Import and Set Nuxt.js options
 let config = require('../nuxt.config.js')
 config.dev = !(app.env === 'production')
 // Instantiate nuxt.js
 const nuxt = new Nuxt(config)
 // Build in development
 if (config.dev) {
  const builder = new Builder(nuxt)
  await builder.build()
 }
 // body-parser
 app.use(bodyParser())
 // mongodb
 // session
 app.keys = ['some session']
 const CONFIG = {
  key: 'SESSION', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. default is false **/
 }
 app.use(session(CONFIG, app))
 // routes
 app.use(async (ctx, next) => {
  await next()
  ctx.status = 200 // koa defaults to 404 when it sees that status is unset
  return new Promise((resolve, reject) => {
   ctx.res.on('close', resolve)
   ctx.res.on('finish', resolve)
   nuxt.render(ctx.req, ctx.res, promise => {
    // nuxt.render passes a rejected promise into callback on error.
    promise.then(resolve).catch(reject)
   })
  })
 })
 app.listen(port, host)
 console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
}
start()

For koa- For the usage of session, you can refer to: Learning cookie and session from koa-session middleware

Login routing

// 登录
router.post('/api/login', async (ctx, next) => {
 const { username, password } = ctx.request.body
 let user,
  match
 try {
  user = await Admin.findOne({ user: username }).exec()
  if (user) {
   match = await user.comparePassword(password, user.password)
  }
 } catch (e) {
  throw new Error(e)
 }
 if (match) {
  ctx.session.user = {
   _id: user._id,
   username: user.user,
   nickname: user.nickname,
   role: user.role
  }
  console.log(ctx.session)
  return (ctx.body = {
   success: true,
   data: {
    username: user.user,
    nickname: user.nickname
   }
  })
 }
 return (ctx.body = {
  success: false,
  err: '密码错误'
 })
})

Written here, the entire function The process is basically completed and very smooth, but for me there is no such thing as smooth sailing code.

session is not defined

Problem

nuxtServerInit ({ commit }, { req, res }) {
  if (req.session && req.session.user) { // res.session is not defined
   const { username, password } = req.session.user
   const user = {
    username,
    password
   }
   commit('SET_USER', user)
  }
 }

No information about the session can be obtained in nuxtServerInit, but other APIs can obtain the session. At that time, because I couldn't find the reason, I once suspected that there was something wrong with the chestnuts. .

Reason

The final problem is still due to my carelessness and neglect of some details. Among the chestnuts given on the official website:

app.post('/api/login', function (req, res) {
 if (req.body.username === 'demo' && req.body.password === 'demo') {
  req.session.authUser = { username: 'demo' }
  return res.json({ username: 'demo' })
 }
 res.status(401).json({ error: 'Bad credentials' })
})

It will The session is saved in req.session, so the session in nuxtServerInit does exist in req.session. However, I use Koa2 and Koa-session. Koa-session parses the cookie to ctx.session, which does not exist in req.session.

Solution

So when injecting nuxt.render, add session to request

app.use(async (ctx, next) => {
  await next()
  ctx.status = 200 // koa defaults to 404 when it sees that status is unset
  ctx.req.session = ctx.session
  return new Promise((resolve, reject) => {
   ctx.res.on('close', resolve)
   ctx.res.on('finish', resolve)
   nuxt.render(ctx.req, ctx.res, promise => {
    // nuxt.render passes a rejected promise into callback on error.
    promise.then(resolve).catch(reject)
   })
  })
 })

I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to deal with async/await wasted performance problem

jQuery implementation of fuzzy query practical case analysis

The above is the detailed content of How to operate nuxt framework for routing authentication and use Koa and Session. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
解读CRISP-ML(Q):机器学习生命周期流程解读CRISP-ML(Q):机器学习生命周期流程Apr 08, 2023 pm 01:21 PM

译者 | 布加迪审校 | 孙淑娟目前,没有用于构建和管理机器学习(ML)应用程序的标准实践。机器学习项目组织得不好,缺乏可重复性,而且从长远来看容易彻底失败。因此,我们需要一套流程来帮助自己在整个机器学习生命周期中保持质量、可持续性、稳健性和成本管理。图1. 机器学习开发生命周期流程使用质量保证方法开发机器学习应用程序的跨行业标准流程(CRISP-ML(Q))是CRISP-DM的升级版,以确保机器学习产品的质量。CRISP-ML(Q)有六个单独的阶段:1. 业务和数据理解2. 数据准备3. 模型

thinkphp是不是国产框架thinkphp是不是国产框架Sep 26, 2022 pm 05:11 PM

thinkphp是国产框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,是为了简化企业级应用开发和敏捷WEB应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。

Python 强大的任务调度框架 Celery!Python 强大的任务调度框架 Celery!Apr 12, 2023 pm 09:55 PM

什么是 celery这次我们来介绍一下 Python 的一个第三方模块 celery,那么 celery 是什么呢? celery 是一个灵活且可靠的,处理大量消息的分布式系统,可以在多个节点之间处理某个任务; celery 是一个专注于实时处理的任务队列,支持任务调度; celery 是开源的,有很多的使用者; celery 完全基于 Python 语言编写;所以 celery 本质上就是一个任务调度框架,类似于 Apache 的 airflow,当然 airflow 也是基于 Python

6个推荐的Python框架,用于构建可解释的人工智能系统(XAI)6个推荐的Python框架,用于构建可解释的人工智能系统(XAI)Apr 26, 2023 am 10:49 AM

AI就像一个黑匣子,能自己做出决定,但是人们并不清楚其中缘由。建立一个AI模型,输入数据,然后再输出结果,但有一个问题就是我们不能解释AI为何会得出这样的结论。需要了解AI如何得出某个结论背后的原因,而不是仅仅接受一个在没有上下文或解释的情况下输出的结果。可解释性旨在帮助人们理解:如何学习的?学到了什么?针对一个特定输入为什么会做出如此决策?决策是否可靠?在本文中,我将介绍6个用于可解释性的Python框架。SHAPSHapleyAdditiveexplanation(SHapleyAdditi

如何在PHP中使用AOP框架如何在PHP中使用AOP框架May 19, 2023 pm 01:21 PM

AOP(面向切面编程)是一种编程思想,用于解耦业务逻辑和横切关注点(如日志、权限等)。在PHP中,使用AOP框架可以简化编码,提高代码可维护性和可扩展性。本文将介绍在PHP中使用AOP框架的基本原理和实现方法。一、AOP的概念和原理面向切面编程,指的是将程序的业务逻辑和横切关注点分离开来,通过AOP框架来实现统一管理。横切关注点指的是在程序中需要重复出现并且

Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Microsoft .NET Framework 4.5.2、4.6 和 4.6.1 将于 2022 年 4 月终止支持Apr 17, 2023 pm 02:25 PM

已安装Microsoft.NET版本4.5.2、4.6或4.6.1的MicrosoftWindows用户如果希望Microsoft将来通过产品更新支持该框架,则必须安装较新版本的Microsoft框架。据微软称,这三个框架都将在2022年4月26日停止支持。支持日期结束后,产品将不会收到“安全修复或技术支持”。大多数家庭设备通过Windows更新保持最新。这些设备已经安装了较新版本的框架,例如.NETFramework4.8。未自动更新的设备可能

KB5013943 2022 年 5 月更新使 Windows 11 上的应用程序崩溃KB5013943 2022 年 5 月更新使 Windows 11 上的应用程序崩溃Apr 16, 2023 pm 10:52 PM

如果你在Windows11上安装了2022年5月累积更新,你可能已经注意到你一直使用的许多应用程序都不像以前那样工作了。强制性安全更新KB5013943正在使某些使用.NET框架的应用程序崩溃。在某些情况下,用户会收到错误代码:0xc0000135。可选更新中报告了类似的问题,但并不普遍。随着2022年5月的更新,该错误似乎已进入生产渠道,这次有更多用户受到影响。崩溃在使用.NETFramework的应用程序中很常见,Discord或MicrosoftTeams等

使用Python进行RFM分析使用Python进行RFM分析Sep 03, 2023 pm 12:45 PM

Python是一种多功能的编程语言,在数据分析和机器学习领域广受欢迎。其简洁性、可读性和丰富的库使其成为处理复杂数据任务的理想选择。其中一个强大的应用是RFM分析,这是一种在营销中根据客户购买行为进行分割的技术。在本教程中,我们将通过使用Python来实施RFM分析的过程来指导您。我们将从解释RFM分析的概念及其在营销中的重要性开始。然后,我们将逐步深入探讨使用Python进行RFM分析的实际方面。在文章的下一部分中,我们将演示如何使用Python为每个客户计算RFM分数,考虑到为最近性、频率和

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools