How can I post data as form data instead of a request payload?

前端 未结 22 2215
庸人自扰
庸人自扰 2020-11-22 00:13

In the code below, the AngularJS $http method calls the URL, and submits the xsrf object as a \"Request Payload\" (as described in the Chrome debugger network t

相关标签:
22条回答
  • 2020-11-22 00:44

    Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer

    var res = $resource(serverUrl + 'Token', { }, {
                    save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
                });
    
                res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
    
                }, function (error) { 
    
                });
    
    0 讨论(0)
  • 2020-11-22 00:45

    You can define the behavior globally:

    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
    

    So you don't have to redefine it every time:

    $http.post("/handle/post", {
        foo: "FOO",
        bar: "BAR"
    }).success(function (data, status, headers, config) {
        // TODO
    }).error(function (data, status, headers, config) {
        // TODO
    });
    
    0 讨论(0)
  • 2020-11-22 00:46

    Just set Content-Type is not enough, url encode form data before send. $http.post(url, jQuery.param(data))

    0 讨论(0)
  • 2020-11-22 00:49

    I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

    .config(['$httpProvider', function ($httpProvider) {
      // Intercept POST requests, convert to standard form encoding
      $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
      $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
        var key, result = [];
    
        if (typeof data === "string")
          return data;
    
        for (key in data) {
          if (data.hasOwnProperty(key))
            result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
        }
        return result.join("&");
      });
    }]);
    
    0 讨论(0)
  • 2020-11-22 00:50

    You can try with below solution

    $http({
            method: 'POST',
            url: url-post,
            data: data-post-object-json,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            transformRequest: function(obj) {
                var str = [];
                for (var key in obj) {
                    if (obj[key] instanceof Array) {
                        for(var idx in obj[key]){
                            var subObj = obj[key][idx];
                            for(var subKey in subObj){
                                str.push(encodeURIComponent(key) + "[" + idx + "][" + encodeURIComponent(subKey) + "]=" + encodeURIComponent(subObj[subKey]));
                            }
                        }
                    }
                    else {
                        str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]));
                    }
                }
                return str.join("&");
            }
        }).success(function(response) {
              /* Do something */
            });
    
    0 讨论(0)
  • 2020-11-22 00:52

    I'm currently using the following solution I found in the AngularJS google group.

    $http
    .post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }).success(function(data) {
        $scope.data = data;
    });
    

    Note that if you're using PHP, you'll need to use something like Symfony 2 HTTP component's Request::createFromGlobals() to read this, as $_POST won't automatically loaded with it.

    0 讨论(0)
提交回复
热议问题