Handling Requests, State, and Middleware in Egg.js
Routing and Controllers
Retrieving GET Request Parameters
Using Query Strings
// Access parameters via query string
const queryParams = this.ctx.request.query;
console.log(queryParams);
this.ctx.body = `The received index value is ${queryParams.index}`;
Using Route Parameters
// Access parameters via route parameters
const userId = this.ctx.params.id;
this.ctx.body = `The received user ID is ${userId}`;
Retrieving POST Request Parameters
To handle POST requests, CSRF protection may need to be disabled during development.
// Configure in config.default.js
config.security = {
csrf: {
enable: false,
},
};
Using RESTful-style routing can simplify route definitions.
router.resources('articles', '/api/articles', controller.articles);
| Method | Path | Controlller.Action |
|---|---|---|
| GET | /articles | app.controller.articles.index |
| GET | /articles/new | app.controller.articles.new |
| GET | /articles/:id | app.controller.articles.show |
| GET | /articles/:id/edit | app.controller.articles.edit |
| POST | /articles | app.controller.articles.create |
| PUT | /articles/:id | app.controller.articles.update |
| DELETE | /articles/:id | app.controller.articles.destroy |
// Render a form at /items/new
async new() {
this.ctx.body = `
<form method='post' action='/items'>
<input name='itemname'>
<button>Submit</button>
</form>
`;
}
// Handle form submission at /items
async create() {
const itemData = this.ctx.request.body;
itemCollection.push(itemData.itemname);
this.ctx.redirect('/items');
}
Plugins
egg-view-nunjucks Template Engine
Install the plugin:
npm install --save egg-view-nunjucks
Configuration:
// plugin.js
module.exports = {
nunjucks: {
enable: true,
package: 'egg-view-nunjucks'
}
};
// config.default.js
config.view = {
defaultViewEngine: 'nunjucks'
};
Create HTML templates in the app/view directory.
// In a controller
await ctx.render('homepage', { items: ['Item A', 'Item B', 'Item C'] });
<!-- app/view/homepage.html -->
<body>
<h1>Item List</h1>
<ul>
{% for element in items %}
<li>{{ element }}</li>
{% endfor %}
</ul>
</body>
egg-cors for Cross-Origin Requests
Install the plugin:
npm install --save egg-cors
Configuration:
// plugin.js
module.exports = {
cors: {
enable: true,
package: 'egg-cors'
}
};
// config.default.js
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};
Frontend example (Vue 3):
import axios from 'axios';
import { ref } from 'vue';
const dataMessage = ref('initial message');
const fetchData = () => {
axios.get('http://127.0.0.1:7001/api/data').then((response) => {
dataMessage.value = response.data;
});
};
Backend route and controller:
// router.js
router.get('/api/data', controller.api.getData);
// controller
async getData() {
this.ctx.body = 'data from egg';
}
Managing User Authentication State
Using Sessions
- Install and configure required plugins.
- Define routes for login actions.
// router.js
router.get('/auth/login', controller.auth.showLogin);
router.post('/auth/login', controller.auth.processLogin);
router.post('/auth/logout', controller.auth.processLogout);
- Login form template.
<!-- login.html -->
<form method="post" action="/auth/login">
<input type="text" name="username">
<input type="password" name="password">
<button>Login</button>
</form>
- Controller logic.
async index() {
const { ctx } = this;
if (ctx.session.currentUser) {
await ctx.render('dashboard', { data: ['Data 1', 'Data 2'] });
} else {
ctx.redirect('/auth/login');
}
}
async showLogin() {
await this.ctx.render('login');
}
async processLogin() {
const username = this.ctx.request.body.username;
const password = this.ctx.request.body.password;
if (username === 'admin' && password === 'secret') {
this.ctx.session.currentUser = username;
this.ctx.redirect('/');
} else {
this.ctx.redirect('/auth/login');
}
}
async processLogout() {
this.ctx.session.currentUser = null;
this.ctx.redirect('/auth/login');
}
Using JWT (JSON Web Tokens)
Install the JWT plugin:
npm install --save egg-jwt
Configuration:
// plugin.js
module.exports = {
jwt: {
enable: true,
package: 'egg-jwt'
}
};
// config.default.js
config.jwt = {
secret: 'your-secret-key-here',
};
Generating a token:
async generateToken() {
const userPayload = { username: 'admin' };
const token = this.app.jwt.sign(userPayload, this.app.config.jwt.secret);
this.ctx.body = token;
}
Verifying a token:
try {
const decoded = this.app.jwt.verify(token, this.app.config.jwt.secret);
this.ctx.body = decoded;
} catch (error) {
this.ctx.body = 'Token verification failed';
}
Integrating with a Vue Frontend
Backend routes and controller:
// router.js
router.post('/api/auth/login', controller.auth.authenticate);
router.get('/api/auth/verify', controller.auth.verifyToken);
// controller/auth.js
const Controller = require('egg').Controller;
class AuthController extends Controller {
async authenticate() {
const credentials = this.ctx.request.body.credentials;
if (credentials.username === 'admin' && credentials.password === 'secret') {
const payload = { username: credentials.username };
const token = this.app.jwt.sign(payload, this.app.config.jwt.secret);
this.ctx.body = {
success: true,
token: token
};
} else {
this.ctx.body = {
success: false,
message: 'Invalid credentials'
};
}
}
async verifyToken() {
const token = this.ctx.request.header.authorization;
try {
const decoded = this.app.jwt.verify(token, this.app.config.jwt.secret);
this.ctx.body = 'Access granted';
} catch (error) {
this.ctx.body = 'Access denied';
}
}
}
module.exports = AuthController;
Frontend Vue component (Login.vue):
<template>
<div>
<form @submit.prevent="submitLogin">
<input v-model="formData.username" type="text">
<input v-model="formData.password" type="password">
<button>Login</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formData: {
username: '',
password: ''
}
};
},
methods: {
submitLogin() {
axios.post('http://127.0.0.1:7001/api/auth/login', {
credentials: this.formData
}).then(response => {
if (response.data.success) {
localStorage.setItem('authToken', response.data.token);
this.$router.push('/dashboard');
}
});
}
}
}
</script>
Vue Router navigation guard:
router.beforeEach((to, from, next) => {
if (to.path === '/login') {
next();
} else {
const token = localStorage.getItem('authToken');
if (token) {
next();
} else {
next('/login');
}
}
});
Middleware
Creating Middleware
Create a file app/middleware/authValidator.js.
function authValidator() {
return async (ctx, next) => {
try {
const authHeader = ctx.request.header.authorization;
const decoded = ctx.app.jwt.verify(authHeader, ctx.app.config.jwt.secret);
if (decoded.username) {
await next();
} else {
ctx.body = {
code: 401,
msg: 'Authentication failed'
};
}
} catch (error) {
ctx.body = {
code: 401,
msg: 'Invalid token'
};
}
};
}
module.exports = authValidator;
Applying Middleware to Routes
// Apply middleware to a specific route
router.get('/api/protected', app.middleware.authValidator(), controller.api.getProtectedData);