Skip to content

Instantly share code, notes, and snippets.

@milon87
Created September 9, 2017 05:37
Show Gist options
  • Select an option

  • Save milon87/f391e54e64e32e1626235d4dc4d16dc8 to your computer and use it in GitHub Desktop.

Select an option

Save milon87/f391e54e64e32e1626235d4dc4d16dc8 to your computer and use it in GitHub Desktop.
how to use x-www-form-urlencoded in react native
var details = {
'userName': 'test@gmail.com',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://identity.azurewebsites.net' + '/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
@stanrud
Copy link
Copy Markdown

stanrud commented Jan 22, 2019

Cool! Thanks 👍

@manishn2184
Copy link
Copy Markdown

am getting 400 :

fetch(url,{
method:'POST',
body: qs.stringify(data),
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
},
}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})

@mguay22
Copy link
Copy Markdown

mguay22 commented Dec 30, 2019

Very nice, thanks! Here is an updated ES8 version:

let encodedForm = [];
Object.entries(form).forEach((key, value) => {
    const encodedKey = encodeURIComponent(key);
    const encodedValue = encodeURIComponent(value);
    encodedForm.push(`${encodedKey}=${encodedValue}`);
});
encodedForm = encodedForm.join('&');
return encodedForm;

@akgupta0777
Copy link
Copy Markdown

can we simplify the form body encoding

@polydevuk
Copy link
Copy Markdown

mguay22
Object.entries(form).forEach((key, value) => {
... should be:
Object.entries(form).forEach(([key, value]) => {

@rakeshpal90
Copy link
Copy Markdown

Really a great solution ever

@murtazavadnagar
Copy link
Copy Markdown

murtazavadnagar commented Feb 6, 2023

Thanks for the solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment