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

前端 未结 22 2247
庸人自扰
庸人自扰 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:37

    As of AngularJS v1.4.0, there is a built-in $httpParamSerializer service that converts any object to a part of a HTTP request according to the rules that are listed on the docs page.

    It can be used like this:

    $http.post('http://example.com', $httpParamSerializer(formDataObj)).
        success(function(data){/* response status 200-299 */}).
        error(function(data){/* response status 400-999 */});
    

    Remember that for a correct form post, the Content-Type header must be changed. To do this globally for all POST requests, this code (taken from Albireo's half-answer) can be used:

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

    To do this only for the current post, the headers property of the request-object needs to be modified:

    var req = {
     method: 'POST',
     url: 'http://example.com',
     headers: {
       'Content-Type': 'application/x-www-form-urlencoded'
     },
     data: $httpParamSerializer(formDataObj)
    };
    
    $http(req);
    
    0 讨论(0)
  • 2020-11-22 00:37

    Use AngularJS $http service and use its post method or configure $http function.

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

    The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

    Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

    http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

    Hope this helps.

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

    As a workaround you can simply make the code receiving the POST respond to application/json data. For PHP I added the code below, allowing me to POST to it in either form-encoded or JSON.

    //handles JSON posted arguments and stuffs them into $_POST
    //angular's $http makes JSON posts (not normal "form encoded")
    $content_type_args = explode(';', $_SERVER['CONTENT_TYPE']); //parse content_type string
    if ($content_type_args[0] == 'application/json')
      $_POST = json_decode(file_get_contents('php://input'),true);
    
    //now continue to reference $_POST vars as usual
    
    0 讨论(0)
  • 2020-11-22 00:42

    This is what I am doing for my need, Where I need to send the login data to API as form data and the Javascript Object(userData) is getting converted automatically to URL encoded data

            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: apiserver + '/authenticate',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj)
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                },
                data: userData
            }).success(function (response) {
                //logics
                deferred.resolve(response);
            }).error(function (err, status) {
               deferred.reject(err);
            });
    

    This how my Userdata is

    var userData = {
                    grant_type: 'password',
                    username: loginData.userName,
                    password: loginData.password
                }
    
    0 讨论(0)
  • 2020-11-22 00:43

    The following line needs to be added to the $http object that is passed:

    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    

    And the data passed should be converted to a URL-encoded string:

    > $.param({fkey: "key"})
    'fkey=key'
    

    So you have something like:

    $http({
        method: 'POST',
        url: url,
        data: $.param({fkey: "key"}),
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    })
    

    From: https://groups.google.com/forum/#!msg/angular/5nAedJ1LyO0/4Vj_72EZcDsJ

    UPDATE

    To use new services added with AngularJS V1.4, see

    • URL-encoding variables using only AngularJS services
    0 讨论(0)
提交回复
热议问题