Skip to content

Instantly share code, notes, and snippets.

@milon87
Created Sep 9, 2017
Embed
What would you like to do?
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
})
@himadripr
Copy link

himadripr commented Jul 31, 2018

Saved a lot of time. Great work

@stanrud
Copy link

stanrud commented Jan 22, 2019

Cool! Thanks 👍

@manishn2184
Copy link

manishn2184 commented Sep 20, 2019

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

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

akgupta0777 commented Dec 29, 2020

can we simplify the form body encoding

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