0

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?

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'
  })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.