$http response Set-Cookie에 액세스할 수 없습니다.
저는 현재 제 백엔드에 angularjs frontend를 쓰고 있는데, 다소 흔한 문제에 부딪히고 있습니다.
서버는 응답으로 쿠키를 다시 보내지만 angular.js에 의해 완전히 무시됩니다('Set-Cookie' 값도 출력할 수 없음).
저는 읽어 보았습니다.
HTTP 헤더의 Set-Cookie는 AngularJS에서 무시됩니다.
Angularjs $http가 응답에서 "Set-Cookie"를 이해하지 못하는 것 같습니다.
안타깝게도 거기서 모든 해결책을 시도해 보았는데 효과가 없는 것 같습니다.
요청발송
응답받음
angular.js(v1.2.10)를 사용하고 있으며, 이것이 제가 요청할 때 사용한 것입니다.
$http.post('/services/api/emailLogin',
sanitizeCredentials(credentials),
{
withCredentials: true
}).success(function(data, status, header) {
console.log(header('Server'));
console.log(header('Set-Cookie'));
console.log(header('Access-Control-Allow-Headers'));
console.log(header('Access-Control-Allow-Methods'));
console.log(header);
}).then(
function(response) {
console.log(response);
return response.data;
});
withCredentials=true
를 요청하기 전에 클라이언트 측에 설정합니다.
Access-Control-Allow-Credentials=true
는 응답을 반환하기 전에 서버 측에 설정됩니다.
눈에 확 띕니다.Set-Cookie
Chrome Developer Tools의 응답 헤더에 있지만 인쇄물은 단지
오직.Set-Cookie
응답 헤더가 출력되지 않습니다.왜 이런 일이 생기는지 궁금합니다.제가 확인할 방법이 있을까요?withCredentials=true
정말 설정되어 있습니까(요청 헤더에서 보지 못했습니다)?
어떤 도움이든 감사히 받겠습니다!
안을 들여다봤습니다.$httpBackend
소스 코드:
xhr.onreadystatechange = function() {
// some code
if (xhr && xhr.readyState == 4) {
var responseHeaders = null,
response = null;
if(status !== ABORTED) {
responseHeaders = xhr.getAllResponseHeaders();
// some code
사용합니다.XMLHttpRequest#getAllResponseHeaders
응답 헤더를 가져옵니다.
약간의 검색 끝에 xmlHttp.getResponseHeader + CORS에서 작동하지 않는 질문을 발견했습니다.
그래서 XHR의 사양이 지원하지 않는다는 것을 알게 되었습니다.SET-COOKIE
, 그래서 angular.js와는 특별한 관계가 없습니다.
http://www.w3.org/TR/XMLHttpRequest/ #모든 응답 헤더 %28%29-
4.7.4 GetAllResponse Headers() 방법
필드 이름이 Set-Cookie 또는 Set-Cookie2인 경우를 제외하고 응답에서 모든 헤더를 반환합니다.
대신 다음을 사용합니다.
다른 모듈이므로 스크립트에 추가해야 합니다.
<script src="angular.js"></script>
<script src="angular-cookies.js"></script>
모듈 종속성에 추가합니다.
var app = angular.module('app',['ngCookies']);
그럼 그냥 이렇게 사용하면 됩니다.
app.controller('ctrl', function($scope, $http , $cookies, $timeout){
$scope.request = function(){
$http.get('/api').then(function(response){
$timeout(function(){
console.log($cookies.session)
});
})
}
})
사용합니다.$timeout
왜냐면$cookies
요약 후에만 브라우저의 쿠키와 동기화할 수 있습니다.
실제로 Angular로 쿠키를 읽어야 하나요, 아니면 설정이 되어 브라우저에서 추가 요청을 전달하면 충분한가요?저는 전자를 작동시킬 수는 없었지만 후자는 매우 유사한 구성으로 빠르게 작동시킬 수 있었습니다.(특히 사용할 수 없었습니다.$cookies
@Ilan 의 권유대로 않았습니다아무 것도 돌려주지 않았습니다.)
각도 측() 에서$httpProvider
withCredentials
기본값:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);
앵귤러에서 할 일은 여기까지입니다.로,에서,면을 $cookies
쿠키를 볼 수는 없지만 저장되어 향후 AJAX 호출과 함께 전달됩니다.
그런 )을 에서 에서() 와 Access-Control-Allow-Credentials
머리말제 백엔드는 Python의 Flask with Flask-Restful이며 다음과 같습니다.
import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
api.decorators = [cors.crossdomain(origin='http://localhost:8100', credentials=True)]
그 정도면 됐어요.이제 Angular(또는 브라우저)에서 쿠키를 설정하고 나중에 요청할 때 완전히 투명하게 반환합니다!
(같은 지적입니다: https://stackoverflow.com/a/19384207/2397068.)
Angular 1.3.14에서는 더 이상 작동하지 않습니다.
저도 같은 문제가 있었습니다.$resource를 사용하고 있으며 Credentials: true로 선언했습니다.
var fooRes = $resource('/address/exemple',
{},
{
bar: {
method: 'POST',
withCredentials: true,
}
}
);
fooRes.bar({
"stuff" : "lorem"
}).$promise.then(function(){
//callback
})
또는 "Access-Control-Allow-Credentials" 헤더를 "true"로 설정할 수 있습니다.
이제 쿠키가 저장되고 $cookie를 사용할 수 있습니다.
도움이 되길 바랍니다.
헤더를 읽을 수 있도록 .htaccess 파일을 수정해야 합니다.
Header set Access-Control-Allow-Headers Content-Type
'access-control-expose-headers', '*'
노드 API를 사용한 예제
router.get('/your-route', async (req, res) => {
//..
res.setHeader('access-control-expose-headers', '*' );
//..
})
언급URL : https://stackoverflow.com/questions/21520890/http-response-set-cookie-not-accessible
'programing' 카테고리의 다른 글
PHP 함수가 정수를 요청할 때 부울 인수를 허용하는 이유는 무엇입니까? (0) | 2023.09.19 |
---|---|
Protractor - 브라우저를 사용할 위치입니다.WaitFor Angular() (0) | 2023.09.19 |
true 또는 false 대신 1 또는 0을 기준으로 Spring @RequestParam 매핑 부울 (0) | 2023.09.19 |
이미지가 div 테두리 안에 머물지 않습니다. (0) | 2023.09.19 |
'appcmd'라는 용어가 cmdlet의 이름으로 인식되지 않습니다. (0) | 2023.09.19 |