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

62,136

Solution 1

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

Solution 2

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',
      })
Share:
62,136
Isaac Gomes
Author by

Isaac Gomes

Updated on September 25, 2021

Comments

  • Isaac Gomes
    Isaac Gomes over 2 years

    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.

  • Moritz Schmidt
    Moritz Schmidt over 6 years
    Thanks, I forgot the JSON.stringify when adding parameters to the body.
  • user938363
    user938363 about 5 years
    Adding json headers is a better solution.
  • Aoudesh Jaiswal
    Aoudesh Jaiswal about 4 years
    and how to pass variable with parameter in body