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

前端 未结 22 2525
庸人自扰
庸人自扰 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);
    

提交回复
热议问题