Set custom Header in Request

2425 views javascript
8

I'm trying to send the following request with Javascript in an react-native environment:

>curl -X GET --header 'Accept: application/json' --header "authorization: Bearer <API-TOKEN>" 'https://api.mydomain.com/v1/foo/bar'

here is my code:

componentDidMount(){
    return fetch('https://api.mydomain.com/v1/foo/bar',{
      headers: {
        "authorization": "Bearer exampleToken"
      }
    })
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson.movies,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }

on my iOS Device the screen is just blank, and I don't receive any error or logging message.

Running the curl command gives me the expected json.

answered question

1 Answer

7

You should use in the following manner;

fetch('https://api.mydomain.com/v1/foo/bar', { 
   headers: new Headers({
     'Authorization': 'Bearer exampleToken'
   })
 });

Instantiating a Headers with each header key,value pair inside.

posted this

Have an answer?

JD

Please login first before posting an answer.