无法绕过angularjs种子应用程序中的CORS

Unable to bypass CORS in angularjs seed app

本文关键字:应用程序 CORS 种子 angularjs      更新时间:2023-09-26

我正在使用angularjs种子应用程序,并尝试使用$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-urlencodedmultipart/form-datatext/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

然后转到网址localhost:8080/index.html,你就是黄金!

我通过使用express.js作为代理服务器解决了这个问题,这也使我能够使用代理来提供静态内容