Convert JSON as FormURL Encoded data using transformRequest

自闭症网瘾萝莉.ら 提交于 2020-01-05 07:06:33

问题


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:


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;
});


来源:https://stackoverflow.com/questions/43962241/convert-json-as-formurl-encoded-data-using-transformrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!