[英]Unable to bypass CORS in angularjs seed app
我正在使用angularjs-seed應用程序,並且嘗試使用$http
從服務器(MarkLogic)獲得JSON響應。 我已經嘗試了3天,嘗試了其他類似stackoverflow答案的每個響應,但無法正常工作。 請幫忙!
瀏覽器返回以下內容:
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
請求,因此只要它是一個簡單的請求 ,您就應該能夠做到。 您的內容類型可能是將請求標記為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
});
或者-您可以設置一個攔截器並將標頭添加到滿足某些條件的所有請求中。
對於可能會被預檢的非簡單請求,除了確保響應頭滿足預檢請求外,您還需要處理更多的請求標頭。 如果您無權訪問服務器(設置響應頭),則必須在其允許的參數范圍內工作。 這是有關CORS的更多信息。
您需要運行http服務器-最簡單的方法是使用python
從項目的主目錄...
python3 -m http.server 8080
然后轉到url localhost:8080/index.html
,您真高興!
我通過使用express.js作為代理服務器解決了這個問題,這也使我能夠在代理中提供靜態內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.