简体   繁体   English

在 AngularJS 的拦截器中准备 http 请求 url

[英]Preparing http request url in interceptors in AngularJS

I tried to prepare http request url in interceptors rather than adding it to the object passed in $http.我试图在拦截器中准备 http 请求 url,而不是将它添加到 $http 中传递的对象中。 Here is the sample of code I tried:这是我尝试过的代码示例:

angular.module('myapp', [])

.service('myservice', function() {
    this.myfunction = function() {
        var req = {method: 'POST', reqName: 'getInfo'};
        return $http(req);
    }
})

.factory('myInterceptor', function() {
    var interceptor = {
        'request': function(config) {
            config.url = "http://www.myapi.com/demo/"+config.reqName;
            return config;
        }
    }
    return interceptor;
})

.config(function($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
})

But I'm getting an error, which says:但我收到一个错误,它说:

Error: [$http:badreq] Http request configuration url must be a string.错误:[$http:badreq] Http 请求配置 url 必须是字符串。

Received: undefined收到:未定义

Any help?有什么帮助吗?

Let me show some tests that proof AngularJS documentation is correct.让我展示一些证明 AngularJS 文档正确的测试。

Some details about Interceptor - http://docs.angularjs.org/api/ng/service/$http#interceptors关于拦截器的一些细节 - http://docs.angularjs.org/api/ng/service/$http#interceptors

 angular.module('myApp', []) .service('service', function($http) { this.myfunction = function() { var req = { method: 'POST', reqName: 'getInfo' }; return $http(req); } }) .factory('myInterceptor', function() { var interceptor = { 'request': function(config) { config.url = "http://www.myapi.com/demo/" + config.reqName; return config; } } return interceptor; }) .config(function($httpProvider) { $httpProvider.interceptors.push('myInterceptor'); }) describe("myApp", function() { beforeEach(module("myApp")); it("executes intercpetor that changes request", inject(function(service, $httpBackend) { $httpBackend.expectPOST("http://www.myapi.com/demo/getInfo").respond(201, []); service.myfunction().then(function(r) { expect(r.config.url).toBe('http://www.myapi.com/demo/getInfo') }) $httpBackend.flush(); })); });
 <link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" /> <script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM