-
Session 인증이 들어간 Axois 통신 사용하기HTML + JAVASCRIPT + CSS 2020. 12. 19. 02:54728x90
기본적으로 Axios를 이용한 통신시 인증 쿠키값을 전달하기 위해서는 아래 설정을 추가 해줘야 합니다.
const axios = require('axios'); // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials // 기본 값은 false 입니다. axios.defaults.withCredentials = true;
그리고 API 서버와 통신을 하면, 다음과 같이 오류가 발생합니다.
Access to XMLHttpRequest at 'http://lahuman.github.io' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
해당 오류의 원인은 Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ 과 같습니다.
인증 정보를 포함한 통신시 Access-Control-Allow-Origin 값이 '*' 일 경우 지원을 하지 않습니다.
Access-Control-Allow-Origin 값이 * 로 설정된 통신 예제
결국 각 서버의 호스트 정보를 cors 설정에 추가 해야 합니다.
아래는 인증 정보 샘플 입니다.
const express = require("express"); const app = express(); const cors = require("cors"); app.use( cors({ origin: [ "http://target.service.com", "https://lahuman.github.io", "http://localhost:8080", ], methods: "GET,HEAD,PUT,PATCH,POST,DELETE", preflightContinue: false, optionsSuccessStatus: 204, credentials: true, }) );
Access-Control-Allow-Origin 값이 호스트에 알맞게 적용된 통신 예제
원인을 알고 나면 문제의 해결이 쉬워집니다.
참고자료
728x90'HTML + JAVASCRIPT + CSS' 카테고리의 다른 글
javascript hoisting (0) 2022.10.24 화면 크기 만큼 이미지를 꽉 채우고 이미지가 클 경우 스크롤이 생기게 하는 예제 (0) 2021.12.24 javascript에서 제공되는 console methods (0) 2019.11.24 느낌표 2개의 의미 (0) 2019.11.20 How to fix this is undefined in Vue. (0) 2019.02.06