Skip to content

Instantly share code, notes, and snippets.

@milon87

milon87/api.js

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

This comment has been minimized.

Copy link

@himadripr himadripr commented Jul 31, 2018

Saved a lot of time. Great work

@stanrud

This comment has been minimized.

Copy link

@stanrud stanrud commented Jan 22, 2019

Cool! Thanks 👍

@manishn2184

This comment has been minimized.

Copy link

@manishn2184 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

This comment has been minimized.

Copy link

@mguay22 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

This comment has been minimized.

Copy link

@akgupta0777 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