让AngularJS的$http 服务像jQuery.ajax()一样工作

先比较下他们的差别

  1. $http的post
    . 请求默认的content-Type=application/json
    . 提交的是json对象的字符串化数据,
    . 后端无法从post中获取,
    . 跨域请求是复杂请求,会发送OPTIONS的验证请求,成功后才真正发起post请求

  2. jQuery.post
    . 使用的是content-Type=application/x-www-form-urlencoded -
    . 提交的是form data,
    . 后端可以从post中获取,
    . 简单跨域请求,直接发送

解决办法有两个:

1. 是后端支持复杂的跨域请求
那么后端就需要设置如下的信息

    def options(self):
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Max-Age', 86400)
        self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
        self.write('')

后端post中拿不到数据,我们需要自己处理request的body,看看python和php的处理方式:
python

#这种写法支持多种content-Type提交
    def POST(self):
        if self.request.headers['Content-Type'].find('application/json') >= 0:
            body = self.request.body
            if body:
                return json.loads(body.decode())
            else:
                return {}                
        else:    
            paras = {}
            for k, v in self.request.body_arguments.items():
                paras[k] = v[-1].decode()
            return paras

php

<?
$params = json_decode(file_get_contents('php://input'));
?>

2. 配置AngularJS
配置$http服务的默认content-Type=application/x-www-form-urlencoded,如果是指配置这个的话,虽然提交的content-Type改了,但是提交的数据依然是个json字符串,不是我们想要的form data形式的键值对,需要实现param方法. Talk is cheap, i show you the code.

angular.module('MyModule', [], function($httpProvider) {
    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function(obj) {
        var query = '',
            name, value, fullSubName, subName, subValue, innerObj, i;

        for (name in obj) {
            value = obj[name];

            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            } else if (value !== undefined && value !== null)
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
        }

        return query.length ? query.substr(0, query.length - 1) : query;
    };

    //一个function数组,负责将请求的body,也就是post data,转换成想要的形式
    // Override $http service's default transformRequest    
    $httpProvider.defaults.transformRequest = [function(data) {
        return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];
});

配合一点$resource的API参考,这个代码就好懂了:
https://docs.angularjs.org/api/ngResource/service/$resource

Note:
上述param方法定义的地方不要使用jQuery.param方法,因为jQuery.param方法会将要处理的对象上的function全执行一边,把返回的值当做参数的值,这是我们不期望的,我们写的这个param方法也是为了解决上面说的content-Type=x-www-form-urlencoded,但是提交的数据依然是json串的问题。

如果不使用$resource,还有一种方法

        $scope.formData = {};
        $http({
                method: 'POST',
                url: '/user/',
                data: $.param($scope.formData), // pass in data as strings
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
            })
            .success(function(data) {
                console.log(data);

                if (!data.success) {
                    // if not successful, bind errors to error variables
                    $scope.errorName = data.errors.name;
                    $scope.errorSuperhero = data.errors.superheroAlias;
                } else {
                    // if successful, bind success message to message
                    $scope.message = data.message;
                }
            });

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

posted @   CooMark  阅读(2602)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 手把手教你更优雅的享受 DeepSeek
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
· 乌龟冬眠箱湿度监控系统和AI辅助建议功能的实现
点击右上角即可分享
微信分享提示