Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to make a post request with JSON data in application/x-www-form-urlencoded #263

Closed
vishalvijay opened this issue Jan 18, 2016 · 21 comments

Comments

@vishalvijay
Copy link

let data = {
    a: "some data",
    b: 33,
    c: [
        {
            name: "XYZ",
            other: true
        },
        {
            name: "ABC",
            other: true
        }
    ]
    d: {
        something: true
    }
}

How to make a POST request with above JSON data, as content-type application/x-www-form-urlencoded using fetch api?

@mislav
Copy link
Contributor

mislav commented Jan 18, 2016

You need to serialize it yourself to a string. If you're using jQuery, then you can use $.param(data) to serialize it. Don't forget to specify the Content-type header for the request.

However, if your server accepts JSON, it would be much easier to just JSON.stringify(data) and post JSON instead.

Anyway, we can't help you with details about communicating with your server. The fetch() standard itself doesn't handle any encoding strategies. It's all left to the user.

@mislav mislav closed this as completed Jan 18, 2016
@vishalvijay
Copy link
Author

Thanks @mislav

Server can't accept JSON data, that is the all problem. I'm trying to solve this with out jquery. Any suggestion?

@mislav
Copy link
Contributor

mislav commented Jan 19, 2016

I can't solve this problem for you. You could take a look at Zepto's $.param implementation and try to copy it. You would have to rewrite it a little bit to not make it dependent on $.isFunction, $.isArray, $.type and $.each.

@dgraham
Copy link
Contributor

dgraham commented Jan 19, 2016

You might also consider using FormData as the post body. Server endpoints that accept application/x-www-form-urlencoded frequently accept multipart/form-data as well.

@vishalvijay
Copy link
Author

👍

@yakirn
Copy link

yakirn commented Mar 29, 2016

For anyone else who might still have this problem, I've implemented mislav suggestion using lodash here:
https://gist.github.com/yakirn/831e5e7fcdfb50fc6c94
It needs more testing, so i'll appreciate any feedback.

@teameh
Copy link

teameh commented Apr 13, 2016

@dgraham using

fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new FormData(postData)
})

results in this formData why I try it...

------WebKitFormBoundarybJk1vnBHdSvQEKdD--

image

@dgraham
Copy link
Contributor

dgraham commented Apr 13, 2016

A FormData request body automatically sets the Content-Type to multipart/form-data. Overriding the header with a different type, like in the above example, probably won't work.

A URLSearchParams request body automatically sets the Content-Type header to application/x-www-form-urlencoded;charset=UTF-8.

https://fetch.spec.whatwg.org/#body-mixin

@teameh
Copy link

teameh commented Apr 13, 2016

That makes sense.

Too bad we need yet another polyfill for that to work..

import URLSearchParams from 'url-search-params';

const searchParams = new URLSearchParams();
for (const prop in params) {
  searchParams.set(prop, params[prop]);
}


fetch(url, {
  method: 'POST',
  body: searchParams
})

And that only works for flat objects..

And than again, when the data is that simple, a manual conversion isn't that hard as well.

const searchParams = Object.keys(params).map((key) => {
  return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  body: searchParams
})

Thanks for the quick reply and the insight!

@zxzl
Copy link

zxzl commented Sep 5, 2016

@tiemevanveen Thanks for simple urlencoder :)

@zhouyingkai1
Copy link

@tiemevanveen Thanks

@nitinja
Copy link

nitinja commented Feb 15, 2017

How I solved this:

I am using "qs" package for stringifying/encoding the json

My Request code:

        fetch('http://localhost:8888/oauth2/token',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          },
          body: qs.stringify({
            grant_type: 'password',
            username: 'user_name',
            password: "user_password"
          })
        })

this makes server call as

image

@LuisHansen
Copy link

I got this working by using JSON.stringify and the correct headers:
image

@pragmat1c1
Copy link

@nitinja This solved it for me! Thanks a lot

@vikas199
Copy link

vikas199 commented Aug 7, 2017

enable to get data should get the data in the array of books
fetch('https://reactnd-books-api.udacity.com/search', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'whatever-you-want',
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, maxResults })
}).then(res => res.json())
.then(data => console.log(data))

@wxianfeng
Copy link

@nitinja
can use qs in React ?

@hifni
Copy link

hifni commented Jan 23, 2018

Where can I get help on fetch?

@SeanFloresDOMO
Copy link

SeanFloresDOMO commented Feb 13, 2018

This is how I solved for that issue. It was also a problem in jsfiddles echo. I got lazy and used jQuery in the end. Hope this helps others. https://jsfiddle.net/6mnk6kkq/

function GetSomeDeferredStuff() {
  var deferreds = [];
  for (let count = 1; count <= 10; count++) {
    var params = {
      html: '<p>Task #'+count+' complete.',
      delay: count
    }

   //Encode the data
   const searchParams = Object.keys(params).map((key) => {
     return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
   }).join('&');

    //Push fetch requests to an array
    deferreds.push(
      fetch("/echo/html/",
      {
          method: "POST",
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          },
          body: searchParams
      })
      .then(r => r.text())
      .then(data => log(data))
    );
  }
  return deferreds;
}

//  Log for debugging
function log(html){
	console.log(html);
	$("div").append(html);
}

// Execute using jQuery or Promise.All() if preferred
$(function() {
    $("a").click(function() {
        var deferreds = GetSomeDeferredStuff();

        $.when.apply($, deferreds).done(function(e,i) {
            $("div").append("<p>All done!</p>");
        });
    });
});

@malpanianshul
Copy link

@nitinja Thanks a lot

@tawfik-1990
Copy link

I have problem with post request authentification while trying to run the code I get error invalide request does anyone know how I could solve this problem, I get this error { error: 'invalid_request' }

const dat = {
'grant_type': 'authorization_code',

          'code':code ,
           "redirect_uri" : redirect
           };

const URLSearchParams = Object.keys(dat).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(dat[key]);
}).join('&');

fetch('https://polarremote.com/v2/oauth2/token',
{

method: 'POST',
headers: {
'Authorization':Basic ${creds},

'Content-Type': 'application/x-www-form-urlencoded',
 'Accept':'application/json; charset=utf-8'

},
data: URLSearchParams

}).then(function(res) {
return res.json();
}).then(function(body) {
console.log(body);
});

@rayj10
Copy link

rayj10 commented Apr 20, 2018

@nitinja I wish I had seen ur post sooner!! been fiddling around with fetch for a week now trying to firgure out if I did the body formatting wrong cos I can't get the API to recognize the body of my request and now finally it's working! YOU'RE A LIFE SAVER!

Repository owner locked as resolved and limited conversation to collaborators Apr 20, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests