我使用业力作为我的角度项目测试运行框架,我的angular 有服务器服务需要访问另一个 Web URL 来获取数据,例如http://localhost:8081/common/countries
获取有关国家/地区的所有信息。我的问题是我的业力从localhost:9876
开始,它需要从http://localhost:8081/common/countries
通过浏览同源策略获取数据,导致跨域问题。所以我在我的控制台中得到以下错误:
Error: Unexpected request: GET http://localhost:8081/common/countries
No more request expected
at Error (<anonymous>)
at $httpBackend (http://localhost:9876/absoluteC:/WebUI/WebUI/test/lib/angular/angular-mocks.js:934:9)
at sendReq (http://localhost:9876/absoluteC:/WebUI/WebUI/vendor/angular/angular.js:9087:9)
at $http (http://localhost:9876/absoluteC:/WebUI/WebUI/vendor/angular/angular.js:8878:17)
at Object.getMock (http://localhost:9876/base/share/services.js:644:17)
at Object.get (http://localhost:9876/base/share/services.js:347:28)
at Object.getCountries (http://localhost:9876/base/share/services.js:221:22)
at Object.clSingleSelectConfig.nationality.getData (http://localhost:9876/base/share/directives.js:146:32)
at http://localhost:9876/base/share/directives.js:192:44
at nodeLinkFn (http://localhost:9876/absoluteC:/WebUI/WebUI/vendor/angular/angular.js:4360:13)
我尝试过的:1 安装 karma 插件 karma-chrome-launcher 并在我的配置文件中添加--disable-web-security
。但它不起作用。2 在标头中设置"访问控制允许源"访问控制允许标头"访问控制允许方法"以允许在服务器响应中进行源访问。
以上都不起作用,那么如何解决我的问题呢?
对于跨域请求,请使用 expectJSONP,并确保使用回调参数。
describe('stackoverflow.activity tests', function () {
var svc, httpBackend;
beforeEach(function (){
module('ngResource');
module('stackoverflow.activity');
inject(function($httpBackend, StackoverflowActivityService) {
svc = StackoverflowActivityService;
httpBackend = $httpBackend;
});
});
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should send the message and return the response', function (){
var returnData = { testing: 'anything'};
httpBackend.expectJSONP('http://api.stackexchange.com/2.1/users/gigablox/timeline?callback=JSON_CALLBACK').respond(returnData);
svc.events({
user:'gigablox',
params:{
callback:'JSON_CALLBACK'
}
}).get(function(user) {
expect(user.testing).toEqual('anything');
});
httpBackend.flush();
});
});
此示例的来源