Convert JSON as FormURL Encoded data using transformRequest

538 views Asked by At

I am trying to convert JSON data as formURL encoded data but still, it isn't working.

My HTTP post

$http.post(API_ENDPOINT.login, credentials, {
    transformRequest: transformRequestAsFormPost
 })

My transform request

'use strict';

define(['app-module'], function(app) {

$app.info('transformRequest initialized');

return app.factory('transformRequestAsFormPost', function() {

    function transformRequest(data, getHeaders) {
        var headers = getHeaders();
        headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
        return (serializeData(data));
    }

    function serializeData(data) {

        if (!angular.isObject(data)) {
            return ((data === null) ? "" : data.toString());
        }

        var buffer = [];

        for (var name in data) {
            if (!data.hasOwnProperty(name)) {
                continue;
            }

            var value = data[name];

            buffer.push(
                encodeURIComponent(name) +
                "=" +
                encodeURIComponent((value == null) ? "" : value)
            );

            console.log(buffer)

        }
        var source = buffer.join("&").replace(/%40/g, "@");
        return (source);
    }
    return (transformRequest);
});
});

I am unable to figure out what am I doing wrong. when I pass any JSON object into that it returns a string.

1

There are 1 answers

1
georgeawg On BEST ANSWER

Due to 5da1256, transformRequest functions can no longer modify request headers. This behavior was unintended and undocumented, so the change should affect very few applications.1

To send a POST request with Content-Type: application/x-www-form-urlencoded:

var config = {
  transformRequest: $httpParamSerializer,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
};

$http.post(API_ENDPOINT.login, credentials, config)
  .then(function(response) {
    console.log("SUCCESS");
}).catch(function(response) {
    console.log("ERROR");
    throw response;
});