How to use Koa and Session for routing authentication in nuxt framework
This time I will bring you how to use Koa and Session for routing authentication in the nuxt framework. What are the precautions for using Koa and Session for routing authentication in the nuxt framework? , the following is a practical case, 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’smiddleware to do route interception. Vuex is also required here. State tree is used to do it.
middleware
middleware/auth.jsexport 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. Orientationlayouts/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/koaRelated dependencies
npm install koa-sessionRewrite 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
ProblemnuxtServerInit ({ 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 requestapp.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:
detailed explanation of the steps to implement fuzzy query with jQuery
detailed explanation of node Async/Await asynchronous programming implementation
The above is the detailed content of How to use Koa and Session for routing authentication in nuxt framework. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.