To use the Node.js Axios library for making HTTP requests with interceptors for automatic JSON parsing in Koa, you can create a custom middleware in your Koa application. Here's how you can do it:
axios
and koa
packages.bashnpm install axios koa
javascriptconst axios = require('axios');
function axiosMiddleware() {
return async (ctx, next) => {
ctx.axios = axios.create({
baseURL: 'https://api.example.com', // Adjust base URL according to your API
timeout: 5000, // Adjust timeout as needed
headers: {
'Content-Type': 'application/json',
// Add any other default headers here
},
});
// Add response interceptor for automatic JSON parsing
ctx.axios.interceptors.response.use(
(response) => {
if (response.headers['content-type'] === 'application/json') {
response.data = response.data ? JSON.parse(response.data) : {};
}
return response;
},
(error) => {
return Promise.reject(error);
}
);
await next();
};
}
module.exports = axiosMiddleware;
javascriptconst Koa = require('koa');
const axiosMiddleware = require('./axiosMiddleware');
const app = new Koa();
// Use Axios middleware
app.use(axiosMiddleware());
// Example route
app.use(async (ctx) => {
try {
// Make a GET request using ctx.axios
const response = await ctx.axios.get('/data');
ctx.body = response.data;
} catch (error) {
ctx.status = error.response.status || 500;
ctx.body = error.response.data || 'Internal Server Error';
}
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
In this example:
axiosMiddleware
that attaches an Axios instance to the Koa context (ctx
) with default configurations such as base URL, timeout, and headers.axiosMiddleware()
to apply the middleware.ctx.axios
with automatic JSON parsing for responses.Adjust the middleware and configurations according to your specific requirements and API endpoints. This setup provides a convenient way to use Axios for making HTTP requests with automatic JSON parsing in a Koa application.