Tanmoy Sarker
Tanmoy Sarker

Reputation: 1266

Using params instead of bearer token in API call in React Native

I am using a lot of API's in my React Native app. In a lot of places i'm using bearer token for different purposes. Right now it looks like:

	getCustomerProfile: async token => {
		return await fetch(
			`MY API`,
			{
				method: 'GET',
				headers: {
					Accept: 'application/json',
					Authorization: `Bearer ${token}`,
					'Content-Type': 'application/json',
				},
			}
		)
			.then(response => response.json())
			.then(json => {
				return json;
			})
			.catch(error => warn(error));
	},

But now i don't want to use headers and just want to use params for getting response. In postman my API works fine with params. But how can i change here to get response using params instead of headers?

Upvotes: 0

Views: 1038

Answers (2)

SMAKSS
SMAKSS

Reputation: 10520

The fetch standard in their documentation, suggests a way for using query params in fetch requests. So all you need to do is to create a param and append it to your URL with searchParams and then make your requestion as usual GET request.

Here it is:

var url = new URL("https://geo.example.org/api"),
    params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

NOTE: You can also follow this thread for more info.

Upvotes: 2

Asad
Asad

Reputation: 573

here is the exapmle code

fetch('your url', 
              {
              method: 'POST',
              headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',         
              },
              body: JSON.stringify(
              {
            "p1": "value1",
            "p2"  :  "value2",
              })
            }).then((response) => response.json())
            .then((responseJson) => {
              // remaining code here 

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

ALternatively from official side

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue'
  })
});

Upvotes: 0

Related Questions