【问题标题】:Convert JSON as FormURL Encoded data using transformRequest使用 transformRequest 将 JSON 转换为 FormURL 编码数据
【发布时间】:2017-10-13 05:17:17
【问题描述】:

我正在尝试将 JSON 数据转换为 formURL 编码数据,但仍然无法正常工作。

我的 HTTP 帖子

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

我的转换请求

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

我无法弄清楚我做错了什么。当我将任何 JSON 对象传递给它时,它会返回一个字符串。

【问题讨论】:

    标签: javascript angularjs json form-data angular-factory


    【解决方案1】:

    由于5da1256,transformRequest 函数不能再修改请求标头。此行为是无意的且未记录在案的,因此更改应该会影响极少数应用程序。1

    使用Content-Type: application/x-www-form-urlencoded 发送 POST 请求:

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

    【讨论】:

    • 谢谢,他们应该记录下来。我搜索了几个小时。
    猜你喜欢
    • 1970-01-01
    • 2019-06-19
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多