Request React Activate with Aces

Asked

Viewed 4,864 times

0

I am trying to make a request with Axios for a server, and for that I need to send an access token. The token is correct, but nothing is loading on the network and the request is not working

componentDidMount() {
    const token = AsyncStorage.getItem('token').then((value) => {
        console.log(value);
    });

    const headers = {
        'Authorization': 'Bearer' + token
    }

    axios.get("http://192.168.0.117/api/produtos", {
        headers: headers
    }).then(function (response) {
        console.log(response.data);
    }).catch(error => {
        console.log(error)
    })

}
  • Luan, on the console you put there after you pick up the token value, is it displaying correctly? Another detail is there in the Bearer where the quotes are together 'Bearer'+ token will return you something like Bearer12345 if the token was 12345. Watch this and tell me here if gave.

  • Good morning, you are displaying the token correctly yes. but the Bearer + token ta appearing {Authorization: "Bearerundefined"}

  • Vlw by touch only so I could solve.

2 answers

0

Good morning friend, I believe your problem is in the asynchronous order, try to use async in your function and use await, as in the example below:

componentDidMount = async () => {

    const token = await AsyncStorage.getItem('token').then((value) => {
        console.log(value);
    });

    const headers = {
        'Authorization': 'Bearer' + token
    }

    await axios.get("http://192.168.0.117/api/produtos", {
        headers: headers
    }).then(function (response) {
        console.log(response.data);
    }).catch(error => {
        console.log(error)
    })

}
  • Continue giving Error: Request failed with status code 401

  • Okay, have you checked if it’s a problem with your route? Or the type of request you’re using. Try to improve your error log using console.log(error.response.data.error); . Another detail also try to take a look at the validadeStatus(); of the Axios present here : https://github.com/axios/blob/4882ce5359c0ea5238de1cda21fb40a0584f9858/test/typescript/axios.ts#L39

0

//I solved the problem as follows.

componentDidMount = async () => {
    const headers = {
        'Authorization': 'Bearer' + await AsyncStorage.getItem('token')
    }
    console.log(headers)
    await axios.get("http://192.168.0.117/api/produtos", {
        headers: headers
    }).then(function (response) {
        console.log(response.data);
    }).catch(error => {
        console.log(error)
    })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.