I am trying to make an api req from one server (localhost:3000) to another server(localhost:3001) but I am getting authentication error 401.
Note:If I hard code the authentication token, I am able to make the request.This let me conclude that I am not setting up the axios authentication header in a right way.
apiFile.ts file
import axios, { AxiosInstance } from 'axios';
import { Dispatch } from 'redux';
import { handleResponse } from './handlers';
import { getDiscussionsAction } from '../../redux/actions/dataActions';
let axiosInstance: AxiosInstance = axios.create();
function addDiscussion(data:String) {
axiosInstance.post('http://localhost:3001/api/addDiscussion',data).then(response=> {
console.log(response)
}).catch(error=>{
console.log('error on adding post',error)
})
}
function setupAxiosInstance(token: string) {
console.log('inside setup Axios Instance')
console.log('token setup Axios',token)
axiosInstance = axios.create({
headers: {
Authorization: 'Bearer ' + token}
});
}
export default {
getDiscussions,
addDiscussion,
setupAxiosInstance
}
Expected: When I setupAxiosInstance(String) and pass token to it, it should set the header with the token for subsequent request.
Actual: Though I can see that setupAxiosInstance(String) method have received token and but in subsequent request (ex:AddDiscussion api req), it does not have the authentication
[. It works when I hard code the token in -'let axiosInstance: AxiosInstance = axios.create();' like
let axiosInstance: AxiosInstance = axios.create({
headers: {
Authorization: 'Bearer fjsdkf.sdjkfksfklsdjjksfshjdfhksndyrndbsjdjasbckcnbsdcb;efjdfnsdklncsncsln'}
});)
And also if I do something like below, it still does not work either.
function setupAxiosInstance(token: string) {
console.log('inside setup Axios Instance')
console.log('token setup Axios',token)
axiosInstance = axios.create({
headers: {
Authorization: 'Bearer ya29.Gl9uB4tmH0GzYyxBOmeICZa7vsNLZXPuj2du3Q4HIBMGQzZhixXWuS5mCNSPzkCzfjYK0-XNTM0bHI_Fmist9bjYU9CdD06ZtzHPs8TCHmAQcG1dryM8u9_LtfOHiaVGzA'}
});
}
If anyone can pointout what I am doing wrong or point me in the right direction?, that would be great.