Mrsmartchoice
Mrsmartchoice

Reputation: 1

Why does my Axios API request return a 401 error while Postman works?

I’m using Axios in a Node.js application to make API requests with different authentication methods (Basic Auth, API Key, and Bearer Token). While these requests work perfectly in Postman, they return a 401 Unauthorized error in my code.

Here’s what I’ve tried:

Code Examples:

  1. Basic Auth:
const response = await axios.get("https://secrets-api.appbrewery.com/all?page=2", {
  auth: {
    username: TESTING_USER,
    password: "TESTING_PASSWORD",
  },
});

  1. API Key:
const response = await axios.get("https://secrets-api.appbrewery.com/filter", {
  params: {
    score: 5,
    apiKey: "MYAPIKEY",
  },
});

3.Bearer Token:

const response = await axios.get("https://secrets-api.appbrewery.com/secrets/42", {
  headers: {
    Authorization: "Bearer MYTOKEN",
  },
});

Expected Behavior: The API should return data as it does in Postman.

Actual Behavior: I receive this error for Basic Auth, API Key, and Bearer Token requests:

Error: Request failed with status code 401

Additional Information: Axios version: 1.4.0 Node.js version: v20.11.1 Postman tests work with the same credentials and endpoints.

Question: Why does Axios return a 401 error while Postman works with the same credentials and endpoints? Are there any differences in how Axios and Postman handle authentication? How can I resolve this issue?

Upvotes: -1

Views: 83

Answers (1)

Bench Vue
Bench Vue

Reputation: 9380

Axios returns a 401 error because it requires precise configuration for headers and authentication, unlike Postman, which may handle encoding and defaults automatically; ensure Axios matches Postman settings exactly.

Using this format


const response = await axios.get('https://secrets-api.appbrewery.com/secrets/42', {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer <your-Token>'
    }
});

const response1 = await axios.get('https://secrets-api.appbrewery.com/all', {
    params: {
        'page': '1'
    },
    auth: {
        username: '<your-username>',
        password: '<your-password>'
    },
    headers: {
        'Content-Type': 'application/json'
    }
});

const response2 = await axios.get('https://secrets-api.appbrewery.com/filter', {
    params: {
        'score': '5',
        'apiKey': '<your-apikey>'
    },
    headers: {
        'Content-Type': 'application/json'
    }
});

demo.js

const axios = require('axios');

(async () => {
    try {
        const response = await axios.get('https://secrets-api.appbrewery.com/secrets/42', {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer 6f279dd4-d65b-4971-bc6a-bde5ab3c5085'
            }
        });
        console.log('Response from /secrets/42:', response.data);
    } catch (error) {
        console.error('Error fetching /secrets/42:', error.message);
    }

    try {
        const response1 = await axios.get('https://secrets-api.appbrewery.com/all', {
            params: {
                'page': '1'
            },
            auth: {
                username: 'my-username',
                password: 'my-password'
            },
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('Response from /all:', response1.data);
    } catch (error) {
        console.error('Error fetching /all:', error.message);
    }

    try {
        const response2 = await axios.get('https://secrets-api.appbrewery.com/filter', {
            params: {
                'score': '5',
                'apiKey': '6eaddd2f-6ecf-499d-8a8a-9cd6adf70bc5'
            },
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('Response from /filter:', response2.data);
    } catch (error) {
        console.error('Error fetching /filter:', error.message);
    }
})();

Result

Response from /secrets/42: {
  id: 42,
  secret: 'I pretend to be a food blogger, taking pictures of my meals at restaurants even though I have no intention of posting them.',
  emScore: 6,
  username: 'foodiepretender',
  timestamp: '2023-06-27 05:09:44 utc'
}
Response from /all: [
  {
    id: 1,
    secret: "I secretly eat ice cream straight from the tub when no one's looking.",
    emScore: 3,
    username: 'user123',
    timestamp: '2023-06-25 12:01:23 utc'
  },
  {
    id: 2,
    secret: 'I pretend to be on important conference calls just so I can have some alone time in my home office and nap.',
    emScore: 6,
    username: 'secretsnacker',
    timestamp: '2023-06-25 13:45:17 utc'
  },
  {
    id: 3,
    secret: 'I have a secret stash of chocolate hidden in my sock drawer to satisfy my sweet tooth.',
    emScore: 2,
    username: 'chocoHoarder',
    timestamp: '2023-06-25 14:30:51 utc'
  },
  {
    id: 4,
    secret: 'I secretly dance in front of the mirror pretending to be a backup dancer for famous singers.',
    emScore: 7,
    username: 'dancingqueen',
    timestamp: '2023-06-25 15:12:36 utc'
  },
  {
    id: 5,
    secret: 'I wear mismatched socks on purpose, just to see if anyone notices.',
    emScore: 2,
    username: 'sockrebel',
    timestamp: '2023-06-25 16:05:09 utc'
  },
  {
    id: 6,
    secret: "I pretend to know how to cook fancy dishes, but I'm really just following YouTube tutorials.",
    emScore: 5,
    username: 'culinaryimposter',
    timestamp: '2023-06-25 17:20:42 utc'
  },
  {
    id: 7,
    secret: "I've named all the plants in my house, and sometimes I have conversations with them.",
    emScore: 4,
    username: 'plantwhisperer',
    timestamp: '2023-06-25 18:15:28 utc'
  },
  {
    id: 8,
    secret: 'I secretly binge-watch reality TV shows while pretending to be productive.',
    emScore: 4,
    username: 'realitytvjunkie',
    timestamp: '2023-06-25 19:03:57 utc'
  },
  {
    id: 9,
    secret: "I talk to my pet fish and imagine they're responding to me with witty comebacks.",
    emScore: 3,
    username: 'fishwhisperer',
    timestamp: '2023-06-25 20:10:22 utc'
  },
  {
    id: 10,
    secret: "I've been known to wear my pajamas under my work clothes for extra comfort during the day.",
    emScore: 2,
    username: 'comfortcrawler',
    timestamp: '2023-06-25 21:07:14 utc'
  }
]
Response from /filter: [
  {
    id: 2,
    secret: 'I pretend to be on important conference calls just so I can have some alone time in my home office and nap.',
    emScore: 6,
    username: 'secretsnacker',
    timestamp: '2023-06-25 13:45:17 utc'
  },
  {
    id: 4,
    secret: 'I secretly dance in front of the mirror pretending to be a backup dancer for famous singers.',
    emScore: 7,
    username: 'dancingqueen',
    timestamp: '2023-06-25 15:12:36 utc'
  },
  {
    id: 6,
    secret: "I pretend to know how to cook fancy dishes, but I'm really just following YouTube tutorials.",
    emScore: 5,
    username: 'culinaryimposter',
    timestamp: '2023-06-25 17:20:42 utc'
  },
  {
    id: 11,
    secret: "I've perfected the art of taking selfies in the bathroom to hide the fact that I'm really just sitting on the toilet.",
    emScore: 7,
    username: 'masteroftoiletselfies',
    timestamp: '2023-06-25 22:15:39 utc'
  },
  {
    id: 14,
    secret: "I've convinced my friends that I'm a great cook, but I actually order takeout and put it on fancy plates.",
    emScore: 6,
    username: 'fakechefextraordinaire',
    timestamp: '2023-06-26 01:20:37 utc'
  },
  {
    id: 21,
    secret: 'I have a secret collection of embarrassing childhood photos that I use to blackmail my siblings.',
    emScore: 8,
    username: 'siblingblackmailer',
    timestamp: '2023-06-26 08:12:44 utc'
  },
  {
    id: 22,
    secret: "I change the language settings on people's phones when they're not looking, just to confuse them.",
    emScore: 6,
    username: 'phoneprankster',
    timestamp: '2023-06-26 09:05:29 utc'
  },
  {
    id: 26,
    secret: 'I have a secret Pinterest board dedicated to my future life as a millionaire, complete with mansion and exotic pets.',
    emScore: 6,
    username: 'futuremillionaire',
    timestamp: '2023-06-26 13:15:53 utc'
  },
  {
    id: 29,
    secret: "I've memorized cheesy pickup lines, just in case I need to lighten the mood in awkward situations.",
    emScore: 5,
    username: 'pickuplinepro',
    timestamp: '2023-06-26 16:01:42 utc'
  },
  {
    id: 33,
    secret: "I purposely mispronounce words to sound fancy, even though I have no idea how they're actually pronounced.",
    emScore: 5,
    username: 'pronunciationmaster',
    timestamp: '2023-06-26 20:15:43 utc'
  },
  {
    id: 40,
    secret: "I've created a secret language with my pet, and we have conversations that only we understand.",
    emScore: 5,
    username: 'animallinguist',
    timestamp: '2023-06-27 03:05:29 utc'
  },
  {
    id: 41,
    secret: "I've convinced my friends that I have a secret talent for juggling, but I can only juggle two balls.",
    emScore: 5,
    username: 'jugglingenthusiast',
    timestamp: '2023-06-27 04:07:51 utc'
  },
  {
    id: 42,
    secret: 'I pretend to be a food blogger, taking pictures of my meals at restaurants even though I have no intention of posting them.',
    emScore: 6,
    username: 'foodiepretender',
    timestamp: '2023-06-27 05:09:44 utc'
  },
  {
    id: 43,
    secret: "I've convinced my friends that I'm a great singer, but in reality, I can't hold a tune.",
    emScore: 5,
    username: 'singingimpostor',
    timestamp: '2023-06-27 06:15:22 utc'
  },
  {
    id: 45,
    secret: 'I secretly wear a superhero cape under my clothes, just in case the world needs saving.',
    emScore: 6,
    username: 'secrethero',
    timestamp: '2023-06-27 08:12:55 utc'
  },
  {
    id: 48,
    secret: "I've convinced my friends that I have a secret talent for magic tricks, but it's all sleight of hand.",
    emScore: 5,
    username: 'magicianimpostor',
    timestamp: '2023-06-27 11:05:32 utc'
  }
]

I registry user/get apikey and token by postman

enter image description here

enter image description here

enter image description here

Upvotes: -1

Related Questions