Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass POST parameters in fetch request? - React Native

This is my code:

componentWillMount() {
  fetch("http://localmachine/localservice/webservice/rest/server.php", {
    method: 'POST',
    body: JSON.stringify({
      wstoken: 'any_token',
      wsfunction: 'any_function',
      moodlewsrestformat: 'json',
      username: 'user',
      password: 'pass',
    })
  })
  .then((response) => response.text())
  .then((responseText) => {
    alert(responseText);
  })
  .catch((error) => {
    console.error(error);
  });
}

In the browser, this request returns a token, but in my react-native android App returns a xml error.

like image 315
Isaac Gomes Avatar asked Feb 02 '17 19:02

Isaac Gomes


2 Answers

This what worked for me

fetch("http://10.4.5.114/localservice/webservice/rest/server.php", {
  method: 'POST',
  headers: new Headers({
             'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
    }),
  body: "param1=value1&param2=value2" // <-- Post parameters
})
.then((response) => response.text())
.then((responseText) => {
  alert(responseText);
})
.catch((error) => {
    console.error(error);
});
like image 50
Jeferson Macedo Avatar answered Oct 14 '22 14:10

Jeferson Macedo


Try to add header in post request.

       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',

       },
       body: JSON.stringify({
         wstoken: 'any_token',
         wsfunction: 'any_function',
         moodlewsrestformat: 'json',
         username: 'user',
         password: 'pass',
      })
like image 33
Santosh Sharma Avatar answered Oct 14 '22 14:10

Santosh Sharma