Repository navigation
Setting Axios Header to Java Backend based on value stored in express session #5955
Replies: 2 comments
|
Hi, it's been almost a year, but how about setting the headers on axios client creation on your first line? |
|
Also, do not set this on a shared Axios singleton with You need a request-scoped value. The cleanest option is to pass the value when making the request: await axiosClient.get('/some-api', {
headers: {
'agent-id': req.session.agentId
}
});If you do not want to pass Example: // requestContext.js
const { AsyncLocalStorage } = require('node:async_hooks');
const requestContext = new AsyncLocalStorage();
module.exports = { requestContext };// express app
const { requestContext } = require('./requestContext');
app.use((req, res, next) => {
requestContext.run(
{
agentId: req.session?.agentId
},
next
);
});Then in your Axios module: const axios = require('axios');
const { requestContext } = require('./requestContext');
const axiosClient = axios.create({
baseURL: '...',
httpsAgent: null,
proxy: false,
timeout: 60000
});
axiosClient.interceptors.request.use(
config => {
const agentId = requestContext.getStore()?.agentId;
if (agentId) {
if (config.headers?.set) {
config.headers.set('agent-id', agentId);
} else {
config.headers = {
...config.headers,
'agent-id': agentId
};
}
}
return config;
},
error => Promise.reject(error)
);
module.exports = axiosClient;Now your existing API calls can stay roughly the same: import api from 'my-api-module';
const { data = {} } = await api.someName();As long as So the short answer is: Axios cannot magically read |
Uh oh!
There was an error while loading. Please reload this page.
I have a node.js express (server-side rendering) frontend app that calls java backend endpoints. I use Axios to call the java endpoints. I need to set a header named "agent-id" into every request express makes to java, the value of that header comes from the express session (
req.session).My Axios code is on another module. I'm importing that module and calling my APIs.
Currently my Axios module code is setup like so:
and I call my APIs from frontend express app like so:
What I've tried
I tried updating req.headers using a app.use middleware but I could not find that header within the axios interceptor.
Ideally I dont want to change my entire API calling structure by passing req obj on every existing API calls, so is there anyway I can globally set the header using express session value for every Java request ?
All reactions