Axios
Framework Koa.js & Axios
Combine the koa.js headers and cookie bearer token to the axios
1. Create Axios Instance
const AxiosInstance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
2. Pass the koa context to the request options
const Koa = require('koa');
const app = new Koa();
app.use(async (koa_context, next) => {
const response = await AxiosInstance.get('/api/some-api', {koa_context})
koa_context.body = response;
// await next();
});
3. Extend the Axios Instance to pre-process koa context
AxiosInstance.interceptors.request.use((config) => {
const { koa_context } = config;
if (koa_context) {
// Auth cookie to bearer token
const koa_cookie = koa_context.cookies;
let cookie_auth_token = koa_cookie.get('token');
let auth_headers = {};
if (cookie_auth_token) {
auth_headers.Authorization = `Bearer ${cookie_auth_token}`;
}
// Koa Header
config.headers = {
...koa_context.request.headers,
...auth_headers,
...config.headers
};
}
return config;
});
Send the upload file koa.js to another API endpoint via axios.js
npm install --save koa-body multer
const axios = require('axios');
const multer = require('@koa/multer');
const Router = require('koa-router');
const router = new Router();
// Configure multer storage and limits
const storage = multer.memoryStorage();
const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 } });
// Define the file upload route
router.post('/upload', upload.single('file'), async (ctx, next) => {
try {
const file = ctx.req.file;
// Create a Blob object from the file buffer
const fileBlob = new Blob([file.buffer], { type: file.mimetype });
// Create a FormData object to package the file data and any other form data
const formData = new FormData();
formData.append('upload_file', fileBlob, file.originalname);
// Make a POST request to the server that handles the file upload
const response = await axios.post('http://example.com/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${ctx.request.headers.authorization}`,
},
});
ctx.status = response.status;
ctx.body = response.data;
} catch (error) {
ctx.status = error.response.status;
ctx.body = error.response.data;
}
});
module.exports = router;