Kasid Khan
Kasid Khan

Reputation: 667

Uable to make a req from one server to another - "Error: Request failed with status code 401"

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.

Upvotes: 0

Views: 61

Answers (2)

Kasid Khan
Kasid Khan

Reputation: 667

In case anybody faced this same issue.I was able to resolve the issue by using LinkContainer from react-router-bootstrap in my component (One of my friend figured it out. Kudos to him.).This was not an issue with axios header authorization but how I was navigating across my react components.

Issue: Though I could see the setupAxiosInstance(String) method have received token and but in subsequent request (ex:AddDiscussion api req), it does not have the authentication.

Reason: Everytime I was navigating to another link using href, there was a page refresh and it was deleting the header authorization.

Solution:

import { LinkContainer } from 'react-router-bootstrap'

use LinkContainer for navigation

<Nav className="mr-auto">
        <LinkContainer to="/discussion">
          <Nav.Link >Discussion</Nav.Link>
        </LinkContainer>
      </Nav>
      <LinkContainer to="/add-discussion">
        <Button variant="primary" id="ask-a-question-button">Ask a Question?</Button>
      </LinkContainer>

or use push.history

<Navbar.Brand href="/home" className="Nav-link">Discussion</Navbar.Brand>
        <Nav className="mr-auto" onSelect={(selectedKey: string) => console.log('selected', selectedKey)}>
          <Nav.Link onClick={() => this.props.history.push("/home")}>
            Home
            {/* <Link to="/">Home</Link> */}
          </Nav.Link>

          <Nav.Link onClick={() => this.props.history.push("/login")}>
            Login
            {/* <Link to="/login/">Login</Link> */}
          </Nav.Link>
        </Nav>
      </Navbar>

but dnt use href to navigate

<Nav className="mr-auto">
  <Nav.Link href="/Discussion">Discussion</Nav.Link>
</Nav>

Upvotes: 0

Asaf Aviv
Asaf Aviv

Reputation: 11760

Instead of reassigning the instance you can set the instance headers like this

function setupAxiosInstance(token: string) {
  console.log('inside setup Axios Instance')
  console.log('token setup Axios',token)
  axiosInstance.defaults.headers.common.Authorization = `Bearer ${token}`;
}

Upvotes: 1

Related Questions