无法在angularjs种子应用程序中绕过CORS
问题描述:
我正在使用angularjs-seed应用程序,我尝试使用$http
从服务器(MarkLogic)获取JSON响应。我已经在它上了3天尝试从其他类似的*答案的每个响应,但无法让它工作。请帮忙!无法在angularjs种子应用程序中绕过CORS
浏览器返回此:
XMLHttpRequest cannot load http://sreddy:8003/v1/search?format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
这里是我的应用程序代码
app.js
'use strict';
// Declare app level module which depends on filters, and services
var app = angular.module('myApp', [
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
]);
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
// to avoid CORS
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('myApp.controllers', []);
app.controller('MyCtrl1', ['$scope', 'dataService', function($scope, dataService) {
$scope.test = "test";
$scope.data = null;
dataService.getData().then(function (dataResponse) {
$scope.data = dataResponse;
});
console.log($scope.data);
}]);
app.controller('MyCtrl2', [function() {
console.log("from MyCtrl2");
}]);
个
services.js
'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
var app = angular.module('myApp.services', []);
app.value('version', '0.1');
app.service('dataService', function($http) {
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'http://sreddy:8003/v1/search?format=json'
});
}
});
答
useXDomain
不是一回事。
你确实有一个同源问题。为了使您的请求发挥作用,您需要根据请求更改标题。由于您正在提出一个简单的GET
请求,您应该可以这么做,只要它是simple request即可。您的内容类型可能是将请求标记为CORS请求的内容。 -
通常,这可以通过你的content-type
头设置为application/x-www-form-urlencoded
,multipart/form-data
,或text/plain
,这样固定的:
$http({
method: 'GET',
url: 'http://sreddy:8003/v1/search?format=json',
headers: {'Content-Type':'text/plain'} //or whatever type
});
或者 - 您可以建立一个拦截器,并添加页眉所有请求某个符合标准。
对于非简单请求,可能得到,除了确保响应标头满足预检请求外,还需要更多地处理请求标头。如果您无法访问服务器(设置响应标头),则必须在允许的参数范围内工作。 Here是关于CORS的更多信息。
答
我解决了这个问题,通过使用express.js作为代理服务器这也使我能够提供静态内容usinf代理
'否'Access-Control-Allow-Origin'标题出现在请求的资源上'意味着它期望从服务器获得标题。你是否将此标题添加到服务器响应中?只有客户端改变才能解决这个问题。 –
啊!我认为它可以在客户端单独处理。让我再试一次(正确的方式)并回到你身边。谢谢你,先生! – Sudhakar
在服务器响应代码中添加了标题并使其工作。谢谢达文。 – Sudhakar