Search code examples
javascriptreactjsaxiospostman

How to do Basic Auth with Axios in react


React Code

import React, { useState, useEffect } from "react";
import axios from "axios";

const Table = () => {
  useEffect(() => {
    console.log("helllllllllllllllo");

    callAPI();
  }, []);

  const callAPI = async () => {
    const url =  "some URL";
    const password = "Secret" ;
    const username = "Consumer Key";

    const data = await axios.get(
      url,
      {},
      {
        auth: {
          username: username,
          password: password,
        },
      }
    );

    console.log("data", data);
  };
  return (
   <div> Hello </div>
  );
};

export default Table;


On Postman, I go to the Authorization Tab and input the Username and password in their respective input fields and get the result but with axios, I getting 401 error. Exact Error being :-

createError.js:16 Uncaught (in promise) Error: Request failed with status code 401
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

Solution

  • You are incorrectly passing the auth headers. In axios GET, first parameter is URL and second parameter is config object. In config object, you can provide auth property for sending basic auth headers.

    const data = await axios.get(url, {
      auth: {
        username: username,
        password: password,
      },
    })