3

The question is simple: how do I post x-www-form-urlencoded content with Aurelia Fetch client?

I need to make the post to a simple ASP.NET Web API server that is using OWIN and Katana for authentication.

An example of what I have already tried:

var loginDTO = new FormData();
loginDTO.append('grant_type', 'password');
loginDTO.append('email', 'test');
loginDTO.append('password', 'test');

return this.http
    .fetch(config.router.token, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: loginDTO
    });

Obviously, that didn't work as intended. How is the correct way to go about posting the data presented in the example?

Tarps
  • 1,928
  • 1
  • 11
  • 27

2 Answers2

6

The aurelia-fetch-client is built on Fetch specification, and it seems that Fetch always sends FormData as Content-Type: multipart/form-data.

To get around this, you have to convert the parameters to a query string and then set the content-type to x-www-form-urlenconed. You can use jQuery or a custom function to convert the object to a query string. Like this:

//jQuery.param returns something like ?param=1&param2=2 and so on
//params = a plain javascript object that contains the parameters to be sent
this.http.fetch(url, {
  body: $.param(params),
  method: 'post',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
.then(response => response.json())
.then(response => { 
   //your magic here
});

Not a good solution, I know, but that's the easiest way I found so far.

Fabio
  • 11,892
  • 1
  • 25
  • 41
  • 2
    This technique no longer works because Aurelia fetch will not permit specifying a body+method: 'GET'+headers I'd prefer not to put the params in the URL, but that does work. So you can remove the body and just specify `fetch(url + params, {...})` –  Apr 02 '16 at 20:55
0

You would use FormData like this:

function sendForm() {
  var formData = new FormData();
  formData.append('email', 'test@test.com');
  formData.append('password', '123456');

  http.post(url, formData);
}