codergirl
codergirl

Reputation: 35

Axios post request failed with status code 401

Hi so Im trying to pull data from https://opentimetable.dcu.ie/ based on the course code so like CASE3, so im trying to pull the weeks timetable, but im new to axios and my post request is failing because of the headers i believe and im not sure why I thought i was doing it correct? im basically trying to get the course identity in the api in the post request below

    import React, { useState, useEffect } from 'react';
    import { View, Text } from 'react-native';
    import axios from 'axios';
    
    export default function LoginScreen() {
      const [user, setUser] = useState({});
    
      const Query = 'CASE3';
    
    
      useEffect(() => {
        async function loadAPI() {
          const response = await axios.post(`https://opentimetable.dcu.ie/broker/api/CategoryTypes/241e4d36-60e0-49f8-b27e-99416745d98d/Categories/Filter?pageNumber=1&query=${Query}`,{headers:{
            "Authorization": "basic T64Mdy7m[",
            "Content-Type" : "application/json; charset=utf-8",
            "credentials": "include",
            "Referer" : "https://opentimetable.dcu.ie/",
            "Origin" : "https://opentimetable.dcu.ie/"}
          });
    
          setUser(response.data);
        }
    
        loadAPI();
      }, []);
    
      return (
        <View style={{ alignItems: "center", marginTop: 24 }}>
          <Text>
            {user.bio}
          </Text>
      </View>
      );
    }

Upvotes: 1

Views: 12698

Answers (1)

Waleed Ahmad
Waleed Ahmad

Reputation: 494

401 error status response code indicates that the request lacks valid authentication credentials. So I was doubtful about your authorization token. However, using postman, I got 200 ok. So the token is fine. So my guess is authorization was failing because of the way you are passing headers. Anyways, Here the code, let me know if it works.

const axios = require('axios');
useEffect(() => {
    const loadAPI = async () => {
        const config = {
            method: 'post',
            url: 'https://opentimetable.dcu.ie/broker/api/CategoryTypes/241e4d36-60e0-49f8-b27e-99416745d98d/Categories/Filter?pageNumber=1&query=CASE3',
            headers: { 
                'Authorization': 'basic T64Mdy7m['
            }
        };

        const response = await axios(config);
        console.log(response);  //just checking if works 
        setUser(response.data);
    }
    loadAPI();
}, []);

Here's postman response: screenshot.png

Upvotes: 1

Related Questions