【问题标题】:AngularJS call working in POSTMAN but not working in AngularJS Application - Response to preflight request doesn't pass access control checkAngularJS 调用在 POSTMAN 中工作但在 AngularJS 应用程序中不起作用 - 对预检请求的响应未通过访问控制检查
【发布时间】:2017-10-12 13:25:02
【问题描述】:

我需要 angularjs 中的 Cors, 我没有将 cors 用于 webapi,因为我使用的是其他人的 api, 我只是想通过使用 angularjs 的基本身份验证来获取数据, 我曾尝试使用 POSTMAN 它工作正常,但使用我的 angularjs 应用程序它不工作 我已经尝试了很多,但它显示错误如下:

加载资源失败:服务器响应状态为 401 (未经授权)index.html:1 XMLHttpRequest 无法加载 https://api.url/token。对预检请求的响应未通过 访问控制检查:没有“Access-Control-Allow-Origin”标头 出现在请求的资源上。原点“http://localhost:63122”是 因此不允许访问。响应的 HTTP 状态代码为 401。

我尝试过如下示例代码:

var myApp = angular.module("myApp", ['ngCookies']);
myApp.config(['$httpProvider', function ($httpProvider) {

    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}

]);
myApp.controller("GetDataController", ["$scope", "$http", function ($scope, $http) {
    $scope.GetToken = function () {
        debugger;
        var appdata = $.param({
            grant_type: 'credentials',
            scope: 'Customer',
        });

        $http({
            async: true,
            crossDomain: true,
            method: 'GET',
             url: 'https://api.url.net/token',
             data: appdata,
            headers: {

                "username": "847fd9f9fg9h7h66jl8ljdggff",
                "password": "302kfsg7fhhjh0dgjngfdjd",
                "Authorization": "Basic Mufdnfaffa8439flg8g"

            }
        }).then(function (response) {
            debugger;
            $scope.displaymessage = response.data;

        }, function errorCallback(response) {
            $scope.displaymessage = response;
            console.log(response)
        });
    };

}])

在 POSTMAN 中工作时我应该在哪里进行更改,为什么它在我的应用程序中不起作用..

【问题讨论】:

    标签: jquery angularjs cors


    【解决方案1】:

    CORS 出现在 跨域 请求的情况下。这意味着,当请求从一个域发送到另一个域时。

    来自Postman 的呼叫不会从domain 发出(因为Postman 就像一个“独立”应用程序,而不是一个托管有分配给它的某个域的网站)。因此,在这种情况下,CORS 不会出现。这解释得更好here

    但是,您的 Angular JS 应用程序必须托管在某个域上。例如,localhostmyexample.com。因此,当您的应用发出相同的调用时,它需要 CORS。

    CORS 必须在服务器上实现,而不是在应用程序中。服务器必须配置为接受来自特定域或所有域的呼叫。您必须联系 Web API 的所有者并要求他们实施 CORS。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-14
      • 2020-07-23
      • 2016-06-05
      相关资源
      最近更新 更多