【问题标题】:How do you send x-www-form-urlencoded data with Angular $resource?如何使用 Angular $resource 发送 x-www-form-urlencoded 数据?
【发布时间】:2015-02-07 03:42:09
【问题描述】:

我正在尝试向仅接受 x-www-form-urlencoded 格式的数据的服务器提交 POST 请求。

当我在 Postman 上测试它时,它可以工作。例如,预览标题如下所示:

    POST /api/signin HTTP/1.1
    Host: myproj.herokuapp.com
    Cache-Control: no-cache
    Content-Type: application/x-www-form-urlencoded

    email=joe%40gmail.com&password=1234567

但是,当我从我的应用程序运行它时,在 Chrome 控制台中查看的标题看起来像:

    Remote Address:10.10.10.250:80
    Request URL:http://myproj.herokuapp.com/api/signIn
    Request Method:POST
    Status Code:400 Bad Request
    Request Headersview source
    Accept:application/json, text/plain, */*
    Accept-Encoding:gzip, deflate
    Accept-Language:en-US,en;q=0.8
    Connection:keep-alive
    Content-Length:53
    Content-Type:application/x-www-form-urlencoded; charset=UTF-8
    Host:rapidit.herokuapp.com
    Origin:http://localhost
    Referer:http://localhost/rapid/v3/src/app/index/
    User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
    Form Dataview parsed
    {"email":"joe@gmail.com","password":"1234567"}

显然,它没有以正确的格式发送数据。

这就是它在我的 Angular 工厂中的样子(带有硬编码的登录数据):

var LoginResource = $resource("http://myproj.herokuapp.com/api/signIn", {}, {
         post: {
            method: "POST",
            isArray: false,
            headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
        }
    });
    var loginUser = function (){
        return LoginResource.post( 
            {
                email: "joe@gmail.com", 
                password: "1234567" 
            }
            ).$promise; //this promise will be fulfilled when the response is retrieved for this call
    };
    return loginUser;

我怎样才能让数据以所需的格式发布?

【问题讨论】:

标签: angularjs forms post ngresource


【解决方案1】:

默认情况下 Angular 使用 application/json 并且将标头设置为形成 url 编码是不够的,您必须实际转换数据,您可以通过使用 $resource 服务上的 de transformRequest 选项来做到这一点。这就是它的样子。

angular.module("AuthModule")
.factory("authResource", ['$resource', 'appSettings', function ($resource, appSettings) {

    return {
        login: $resource(appSettings.serverPath + '/Token', null,
           {
               loginUser: {
                   method: 'POST',
                   headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                   transformRequest: function (data, headersGetter) {
                       var str = [];
                       for (var d in data)
                           str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                       return str.join("&");
                   }
               },
           })
    }

}]);

P/D:这不是我写的。这段代码取自 Multiplesight 的课程,名为 Angular Front to Back with Web API。

【讨论】:

  • 最好使用$httpParamSerializerJQLike
【解决方案2】:

从 angularjs 1.4 开始,你可以使用$httpParamSerializer:

function transformUrlEncoded(data) {
    return $httpParamSerializer(parameters); 
}

...

$resource('http://myproj.herokuapp.com/api/signIn', {}, {
    post: {
        method: "POST",
        headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: transformUrlEncoded
    }
});

【讨论】:

【解决方案3】:

我遇到了类似的问题,AngularJS $resource 服务默认以 JSON 格式发布数据,即如果您检查请求中的 Content-type 标头,您将看到 Content-type: application/json

在我的情况下,我的服务器可以处理这些有效负载,但找到了一个 Google thread 可能对你的情况有所帮助。

【讨论】:

    【解决方案4】:

    这是与 AngularJS 的 Symfony 表单进行通信的非常好的方式:

    感谢 s1moner3d 的提示

    class AngularForm
    {
    constructor($scope, $http, $httpParamSerializerJQLike) {
        'ngInject';
        this.http = $http;
        this.input= '';
        this.$httpParamSerializerJQLike = $httpParamSerializerJQLike;
    }
    
    sendForm(){
    
        let conf = {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            url: '/api/input',
            data: this.$httpParamSerializerJQLike({'name_of_form': {'input':this.input}}),
        }
    
        this.http(conf).then( (response)=>{
            //success
        }, (response)=> {
            //error :(
        });
    
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2020-08-12
      • 2019-05-04
      相关资源
      最近更新 更多