Search code examples
axiosaws-api-gatewayamazon-cognito

What causes Axios to throw a 'Network Error' when sending authenticated requests to AWS API Gateway through Cognito?


I am developing a web app. I have issues with authenticating access to my API gateway. When I run without Authorisation I can get the results. I read elsewhere that network error is due to CORS and I have implemented that and it was working without Authorisation.

My API gateway is working because when without authorization I am able to call and get the result:

My code:

const Dashboard = '/v1/dashboard/overview';

export default function Success() {
  useEffect(() => {
    const testAPI = async () => {
      try {
        const response = await axios.post(Dashboard);
        console.log(response.data.data);
      } catch (err) {
        console.log(err);
      }
    };
    testAPI();
  }, []);
  return;
}

and the results I get from my API call is:

['Data']

and my lambda function attached to my API gateway:

import json

def lambda_handler(event, context):
    print(event)
    
    response = {
    "category": "Success",
    "command": "Overview",
    "data": ['Data']
}

    return {
        'statusCode': 200,
        'headers': {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*"
        },

        'body': json.dumps(response)
    }

When I set my Method request Auth set to my cognito userPool to get authentication I suddenly got network errors. the idToken is the actual jwtToken in the string.

My code:

const Dashboard = '/v1/dashboard/overview';

export default function Success() {
  useEffect(() => {
    const testAPI = async () => {
      try {
        const response = await axios.post(
          Dashboard,
          {},
          {
            headers: {
              Authorization: idToken,
            },
          }
        );
        console.log(response.data.data);
      } catch (err) {
        console.log(err);
      }
    };
    testAPI();
  }, []);
  return;
}

I get this error:

AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}

I tested with Postman and I managed to get the results without any issues. This means I have taken the correct jwtToken to verify, which I double-checked with Authorizers in AWS API gateway.


Solution

  • Solved!

    Set my API gateway to allow CORS.