Search code examples
angularangular2-http

Angular2 Http not sending POST request with form data


I posted this question twice on stackoverflow and I got some down vote by people who did not understand the problem.

The Problem

Moltin api requires that body data in post request sent to the route https://api.molt.in/oauth/access_token come as application/x-www-form-urlencoded only, it does not support application/json, don't ask me why cause I don't know.

So I needed to send a post request with angular2 that fulfils all of that, so I used the code below.

let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers});

let body = {
    client_id: env.MOLTIN_CLIENT_ID,
    grant_type: 'implicit'
 }

this.http.post('https://api.molt.in/oauth/access_token', body, options)
  .subscribe((result) => {
    console.log(result, 'result reached')
  }, (err) => {
    console.log(err, 'error reached');
  });

But the above code never works, the formdata is parsed wrongly so the server returns the error

XMLHttpRequest cannot load https://api.molt.in/oauth/access_token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 400.

The reason why this error is thrown, is because during the preflight the browser sends an OPTIONS request which the server does not acknowledge.

I also tried stringifying the body values using JSON.stringify(body), but this did not help.

PS I have the solution that is why I am making this post so others can benefit from it, I will post it shortly below

Also Note: That I am using a 3rd party API and cannot modify anything there


Solution

  • After searching through the documentation for several hours, I found URLSearchParams and decided to try it, lo and behold it worked.

    Below is the final solution

     let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
     let options = new RequestOptions({headers});
     let  body = new URLSearchParams();
     body.append('client_id', env.MOLTIN_CLIENT_ID);
     body.append('grant_type', 'implicit');
    
    this.http.post('https://api.molt.in/oauth/access_token', body.toString(), options)
      .subscribe((result) => {
        console.log(result, 'result reached')
      }, (err) => {
        console.log(err, 'error reached');
      });