How to force Angular2 to POST using x-www-form-urlencoded

For Angular > 4.3 (New HTTPClient) use the following:

let body = new URLSearchParams();
body.set('user', username);
body.set('password', password);

let options = {
    headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};

this.http
    .post('//yourUrl.com/login', body.toString(), options)
    .subscribe(response => {
        //...
    });

Note 3 things to make it work as expected:

  1. Use URLSearchParams for your body
  2. Convert body to string
  3. Set the header’s content-type

Attention: Older browsers do need a polyfill! I used: npm i url-search-params-polyfill --save and then added to polyfills.ts: import 'url-search-params-polyfill';

Leave a Comment