设置$httpProvider及拦截器

本文详细介绍了如何在AngularJS应用中配置$httpProvider,并实现请求与响应的拦截器,以增强错误处理和添加全局请求头等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置$httpProvider及拦截器

var app = angular.module('myApp', []);

// 声明一个拦截器工厂服务
app.factory("myInterceptor", function () {
    // 此处可以设置4个属性:request、response、requestError、responseError
    return {
        request: function (config) {
            // 可以修改配置对象
            config.headers.custmInfo = "Tom";
            console.log(config)
            return config;
        },
        response: function (config) {
            console.log(config)
            return config;
        },
        requestError: function (rejection) {
            console.log(rejection)
            return rejection;
        },
        responseError: function (rejection) {
            console.log(rejection)
            return rejection;
        }
    }
});

app.config(function ($httpProvider) {
// 修改默认Content-Type为url-encoded
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www.form-urlencoded;charset=utf-8";
    $httpProvider.defaults.headers.put["Content-Type"] = "application/x-www.form-urlencoded;charset=utf-8";
// 设置默认缓存
    $httpProvider.defaults.cache = true;

    // 注册一个拦截器
    $httpProvider.interceptors.push("myInterceptor");
});

// 创建Controller,测试$http如何与服务器交互
app.controller("MyController", function ($scope, $http, $cacheFactory) {
 $http.get("data/users.json").success(function (data) {  //get方法返回的还是promise对象
        $scope.users = data.users;
    })
})
<h2>设置$httpProvider及拦截器</h2>
<hr>
<button ng-click="getUsers()">获取用户列表</button>
<ul>
    <li ng-repeat="user in users">
        姓名:{{user.name}}
        <span>年龄:{{user.age}}</span>
    </li>
</ul>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值