programing

자격 정보가 있는 AngularJS

kakaobank 2023. 3. 18. 08:46
반응형

자격 정보가 있는 AngularJS

Angular를 작업하고 있는데JS 프로젝트: AJAX 콜을 restfull 웹 서비스로 전송해야 합니다.이 웹 서비스는 다른 도메인에 있기 때문에 서버에서 cors를 활성화해야 했습니다.다음 헤더를 설정하여 이 작업을 수행했습니다.

cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

Angular에서 AJAX 요청을 보낼 수 있습니다.JS를 백엔드로 전송하는데 세션 속성을 가져오려고 하면 문제가 발생합니다.이는 sessionid cookie가 백엔드로 전송되지 않기 때문이라고 생각합니다.

credentials를 true로 설정하여 jQuery에서 이 문제를 해결할 수 있었습니다.

$("#login").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/login",
        data : '{"identifier" : "admin", "password" : "admin"}',
        contentType : 'application/json',
        type : 'POST',
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log(data);
        }
    })
});

$("#check").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/ping",
        method: "GET",
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            console.log(data);
        }
    })
});

제가 직면한 문제는 Angular에서 이 기능을 사용할 수 없다는 것입니다.$http 서비스를 사용하는 JS.이렇게 해봤어요.

$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}).
            success(function(data) {
                $location.path('/');
                console.log(data);
            }).
            error(function(data, error) {
                console.log(error);
            });

내가 뭘 잘못하고 있는지 누가 말해줄래?

다음과 같이 구성 개체를 전달해야 합니다.

$http.post(url, {withCredentials: true, ...})

또는 이전 버전:

$http({withCredentials: true, ...}).post(...)

다른 질문도 참조해 주세요.

앱 구성 기능에서 다음을 추가합니다.

$httpProvider.defaults.withCredentials = true;

모든 요청에 대해 이 헤더가 추가됩니다.

주입하는 것을 잊지 마세요.$httpProvider

편집 : 2015-07-29

다음은 다른 해결 방법입니다.

HttpIntercepter는 공통 파라미터뿐만 아니라 공통 헤더 추가에도 사용할 수 있습니다.

설정에 다음을 추가합니다.

$httpProvider.interceptors.push('UtimfHttpIntercepter');

그리고 이름을 붙여 공장을 만든다.UtimfHttpIntercepter

    angular.module('utimf.services', [])
    .factory('UtimfHttpIntercepter', UtimfHttpIntercepter)

    UtimfHttpIntercepter.$inject = ['$q'];
    function UtimfHttpIntercepter($q) {
    var authFactory = {};

    var _request = function (config) {
        config.headers = config.headers || {}; // change/add hearders
        config.data = config.data || {}; // change/add post data
        config.params = config.params || {}; //change/add querystring params            

        return config || $q.when(config);
    }

    var _requestError = function (rejection) {
        // handle if there is a request error
        return $q.reject(rejection);
    }

    var _response = function(response){
        // handle your response
        return response || $q.when(response);
    }

    var _responseError = function (rejection) {
        // handle if there is a request error
        return $q.reject(rejection);
    }

    authFactory.request = _request;
    authFactory.requestError = _requestError;
    authFactory.response = _response;
    authFactory.responseError = _responseError;
    return authFactory;
}

설명:

$http.post(url, {withCredentials: true, ...}) 

그래야 한다

$http.post(url, data, {withCredentials: true, ...})

https://docs.angularjs.org/api/ng/service/$http에 따라

언급URL : https://stackoverflow.com/questions/13741533/angularjs-withcredentials

반응형