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¶m2=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',
})
Author by
Isaac Gomes
Updated on September 25, 2021Comments
-
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 over 6 yearsThanks, I forgot the JSON.stringify when adding parameters to the body.
-
user938363 about 5 yearsAdding json headers is a better solution.
-
Aoudesh Jaiswal about 4 yearsand how to pass variable with parameter in body