Reputation: 1546
so I have setup an interceptor for axios, and I am adding a custom header to my requests. However, when i check in my server code. The header is only received in OPTIONS
request.
class ChainInterceptors {
constructor(config) {
this.cleanConfig = { ...config };
}
build() {
return this.cleanConfig;
}
}
export class ReqInterceptor extends ChainInterceptors {
constructor(config) {
super(config);
}
setLog() {
this.cleanConfig.headers['Respond-By'] = // some value;
return this;
}
}
And I am implementing it in the following manner:
export const request = {
init() {
const token = getItem('token');
const request = axios.create({
httpsAgent: new https.Agent({ keepAlive: true }),
baseURL: LOCAL_URL,
headers: {
authorization: `bearer ${token}`,
'Content-Type': 'application/json',
},
});
this.attachInterceptor(request);
return request;
},
attachInterceptor(request) {
request.interceptors.request.use(config => {
return new ReqInterceptor(config).setLog().build();
});
request.interceptors.response.use(
response => {
// response interceptors
},
error => {
// Do something with response error
return Promise.reject(error);
}
);
},
get() {
return this.init().get.apply(null, arguments);
},
// and other methods...
};
As I said above, the Respond-By
header is only present in my OPTIONS
request. Your guidance is much appreciated.
Upvotes: 2
Views: 5745
Reputation: 3017
I use the following setting in the interceptor to pass token and the current language. The current language is the custom header, I need to detect the current language that the user selects from the Client side.
below config.headers["lang"] = ${lang}
; is the custom header.
From the server-side, I get it by _httpContextAccessor.HttpContext.Request.Headers["lang"]
export function setupAxios(axios, store) {
axios.interceptors.request.use(
config => {
const {
auth: { authToken },
i18n: { lang }
} = store.getState();
// console.log("language => ", lang);
// console.log("setupAxios => ", store.getState());
if (authToken) {
config.headers.Authorization = `Bearer ${authToken}`;
config.headers["lang"] = `${lang}`;
}
store.dispatch(httpRequest.actions.startRequest(true));
return config;
},
err => {
store.dispatch(httpRequest.actions.endRequest(false));
return Promise.reject(err);
}
);
axios.interceptors.response.use(
response => {
store.dispatch(httpRequest.actions.endRequest(false));
return response;
},
err => {
store.dispatch(httpRequest.actions.endRequest(false));
return Promise.reject(err);
}
);
}
Upvotes: 4