AngularJS调用在POSTMAN中工作但不在AngularJS应用程序中工作 - 对预检请求的响应未通过访问控制检查

时间:2017-05-13 08:40:39

标签: jquery 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中进行更改,为什么它在我的应用程序中不起作用..

1 个答案:

答案 0 :(得分:1)

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

来自Postman的来电不会从domain发送(因为Postman就像是一个'独立'应用,而不是托管了某个域的网站)。因此CORS在这种情况下不会出现。这可以更好地解释here

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

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