Response
Framework Koa.js Response
Response the correct http code on the koa.js
const Koa = require('koa');
const KoaApp = new Koa();
KoaApp.use(async (ctx, next) => {
// Check if the user is authenticated
if (!ctx.isAuthenticated()) {
ctx.response.status = 401; // Unauthorized
ctx.response.body = { error: 'Authentication failed' };
} else {
// Perform some action if the user is authenticated
ctx.response.status = 200; // OK
ctx.response.body = { message: 'Hello, world!' };
}
});
KoaApp.listen(3000);
Set the http code 302, 307 koa redirect response
koa_context.status = 302;
// koa_context.status = 301;
koa_context.set('Location', 'https://my-redirect-url.com/');
Set the redirect response on the koa.js and axios
const Koa = require('koa');
const KoaApp = new Koa();
const AxiosHttp = require('axios');
const myRedirectMiddleware = async (koa_context, next) => {
try {
let config = {
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
}
};
let response = await AxiosHttp.get(url, config);
return response;
} catch (error) {
if (error.response) {
// Get status code
const redirect_status_code = error?.response?.status;
koa_context.status = redirect_status_code;
if([301, 302, 307].includes(redirect_status_code)) {
// if the status code is the redirect status code then set the redirect information to the koa context
// Get redirect url
const redirect_url = error?.response?.headers?.location;
if (redirect_url) {
koa_context.set('Location', redirect_url);
}
}
} else {
throw error;
}
}
}
KoaApp.use(myRedirectMiddleware);