Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a project that needs to use Angular2 (final) to post to an old, legacy Tomcat 7 server providing a somewhat REST-ish API using .jsp pages.

This worked fine when the project was just a simple JQuery app performing AJAX requests. However, the scope of the project has grown such that it will need to be rewritten using a more modern framework. Angular2 looks fantastic for the job, with one exception: It refuses to perform POST requests using anything option but as form-data, which the API doesn't extract. The API expects everything to be urlencoded, relying on Java's request.getParameter("param") syntax to extract individual fields.

This is a snipped from my user.service.ts:

import { Injectable }    from '@angular/core'; import { Headers, Response, Http, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map';  @Injectable() export class UserService {     private loggedIn = false;     private loginUrl = 'http://localhost:8080/mpadmin/api/login.jsp';     private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});      constructor(private http: Http) {}      login(username, password) {         return this.http.post(this.loginUrl, {'username': username, 'password':  password}, this.headers)             .map((response: Response) => {                 let user = response.json();                 if (user) {                     localStorage.setItem('currentUser', JSON.stringify(user));                 }             }         );     } } 

No matter what I set the header content type to be, it always ends up arriving as non-encoded form-data. It's not honoring the header I'm setting.

Has anyone else encountered this? How do you go about forcing Angular2 to POST data in a format that can be read by an old Java API using request.getParameter("param")?

Edit: For anyone else who finds this in the future, the solution is actually really simple. Set the body of the post like this:

let body = `username=${username}&password=${password}`;` 

See Brad's example below.

like image 808
Damon Kaswell Avatar asked Oct 04 '16 23:10

Damon Kaswell


People also ask

How do I send a POST request with X-www-form-Urlencoded body in Postman?

If your API requires url-encoded data, select x-www-form-urlencoded in the Body tab of your request. Enter your key-value pairs to send with the request and Postman will encode them before sending.

How do I use application X-www-form-Urlencoded?

To use it, we need to select the x-www-form-urlencoded tab in the body of the request. We need to enter the key-value pairs for sending the request body to the server, and Postman will encode the desired data before sending it. Postman encodes both the key and the value.

What is x-www-form-urlencoded?

The application/x-www-form-urlencoded content type describes form data that is sent in a single block in the HTTP message body. Unlike the query part of the URL in a GET request, the length of the data is unrestricted.


1 Answers

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';

like image 173
Mick Avatar answered Sep 29 '22 11:09

Mick