解决:angularjs has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

先上轮子:
https://stackoverflow.com/questions/20754489/access-control-allow-origin-and-angular-js-http

'use strict';

angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });
    }])
    .controller('apart1', function ($scope) {
        $scope.name = "I am a partamter of app myApp.view3 controller aasdsadsadsd";
        $scope.userName = "请输入用户名称";
        $scope.password = "请输入用户密码";
    })
    .controller('View1Ctrl', function ($scope, $http) {
        $scope.userNamePlaceholder = "请输入用户名称";
        $scope.passwordPlaceholder = "请输入用户密码";
        $scope.userName = "";
        $scope.password = "";


        $scope.aStringInputPlaceholder = "请输入待加密字符串";
        $scope.aStringOutputPlaceholder = "这里输出加密后字符串";
        $scope.aStringInput = "";
        $scope.aStringOutput = "";

        $scope.requestApiForConverToBase64=function () {
            $http({
                method: 'GET',
                url: 'https://www.runoob.com/try/angularjs/data/sites.php',
                headers:{'Content-Type': 'application/json',
                    "Access-Control-Allow-Origin": "*",
                    'Accept': 'application/json'}
            }).then(function successCallback(response) {
                $scope.aStringOutput = response.data;
                console.log("--------1");
            }, function errorCallback(response) {
                // 请求失败执行代码
                console.log("--------2");
            });
        }
    });

核心解决办法:

headers:{‘Content-Type’: ‘application/json’,
“Access-Control-Allow-Origin”: “*”,
‘Accept’: ‘application/json’}

    原文作者:致学无忧
    原文地址: https://www.jianshu.com/p/9a5e0789b658
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞