I have the following code in my component:
fetch('https://domain.com/api', {
method: 'POST',
headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
body: JSON.stringify({
key: 'value'
})
}).
then((response) => {
console.log('Done', response);
});
And every time the request is a GET (checked server logs). I thought it was something to do with CORS
(but apparently no such thing in react-native
) and ATS (but already turned off by default, plus my domain is HTTPS). I've tried from a browser and from a curl
and it worked perfectly, so a priori no issue on server configuration. Any idea what's going on here?
I'm using the latest react-native
version.
A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.
React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. You may refer to MDN's guide on Using Fetch for additional information.
React Fetch POST examplestringify() on the object before passing it in the body of the request and set: "post" for method. "application/json" for the header Content-Type.
To trigger a Post request from the UI side in react -native, we can send the Request option as a second Parameter. Project Structure: The project should look like this: Example: Here, we are sending request options as a second parameter along with the body. This body is handled in API.
After further digging, it was definitely an issue with the API + fetch
. I was missing a slash at the end of the URL and the API issued a 301, that fetch
didn't handle correctly. So I don't know if there is something to fix in the fetch function (and underlying mechanisms) but this fixed my issue :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With