Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch() doing GET instead of POST on react-native (iOS)

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.

like image 887
mvdb Avatar asked Aug 11 '16 15:08

mvdb


People also ask

Does fetch use Get or Post?

A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.

Does fetch work with React Native?

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.

How do I send a POST request with fetch react?

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.

How do I request a post in React Native?

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.


1 Answers

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 :)

like image 58
mvdb Avatar answered Nov 12 '22 09:11

mvdb