axios get request return request failed with error 400

Viewed 37063

I need help on solving this issue. I am new with react native and javascript. Now I am trying to hook up the react native application with API. This process require me to get the token first by axios.post before I can do axios.get to fetch the data.

Long story short, below is my code snippet for both.

... // code 
const TOKEN_URL = 'https://test.co/testing/tokens'
const DATA_URL = 'https://test.co/testing/data/page1'

const getToken = () => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

//'export' here is for use in other code: example onPress function
export const fetchDriver = () => {
    const config = {
        headers: {
            'Bearer': getToken()
        }
    };

    axios.get(DRIVER_URL, config)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });            
};

My expected console log would be something like this

{
    "timestamp": 1510038433,
    "verb": "GET",
    "object": "student",
    "data": {
        "age": "12",
        "id": "90000",
        "name": "Test Student",
        "emergencyName": "asd",
        "createdAt": "2017-10-04T05:39:39+00:00"
    }
}

But I keep getting error saying Request failed with status code 400

I am using Expo to develop this app.

Detail on the error is like this

- node_modules/axios/lib/core/createError.js:16:24 in createError
- node_modules/axios/lib/core/settle.js:19:6 in settle
- node_modules/axios/lib/adapters/xhr.js:78:13 in handleLoad
- node_modules/event-target-shim/lib/event-target.js:172:43 in dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:540:23 in 
setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:381:25 in 
__didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:182:12 in 
emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:306:47 in 
__callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:108:26 in 
<unknown>
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:269:6 in 
__guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:107:17 in 
callFunctionReturnFlushedQueue

I do not have any authorization to edit the api/server if the error comes from there.

Please help me if there is any point that I have been missing out in the snippet. Thank you for your help and suggestion.

3 Answers

sidenote, you forgot to return inside getToken

I'll just give you back story on why this happens. Promises are asynchronous, so is your axios call. Therefore you need to somehow wait for first call result. Otherwise if you put const a = axiosCall() and try to use it right away the a value would be Pending (not a string tho).

For that you can use promises or async/await. I'll show you proper approach with promises. I've just copied your code and refactored it a bit. Also remember that driver is still a promise so you need to handle it as other things.

const getToken = () => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

//'export' here is for use in other code: example onPress function
export const fetchDriver = () => {
    const config = {
        headers: {
            'Bearer': getToken()
        }
    };

    axios.get(DRIVER_URL, config)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });            
};

You are not chaining your requests. You have to wait till you get the token to be able to use it.

Something like this

getToken

const getToken = () => {
    return axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

fetchDriver

export const fetchDriver = () => {
  return getToken().then(token => {
    const config = {
      headers: {
        'Bearer': token
      }
    };

    return axios.get(DRIVER_URL, config)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  });
}

You need to wait until token api get return response and after that You need make second api call with token

change like this

getToken : change to async function

const async getToken = () => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
    //console.log(response.data.token);
    return response.data.token;
    })
    .catch((error) => {
        console.log(error);
    });
};

fetchDriver : add await while calling getToken function

export const fetchDriver = () => {
    const config = {
        headers: {
            'Bearer': await getToken()
        }
    };

    axios.get(DRIVER_URL, config)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });            
};
Related