• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Session 인증이 들어간 Axois 통신 사용하기

04 Jun 2020

Reading time ~1 minute

Session 인증이 들아간 Axios 통신 시 유의 사항

기본적으로 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 값이 호스트에 알맞게 적용된 통신 예제

원인을 알고 나면 문제의 해결이 쉬워집니다.

참고자료

  • Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’
  • cors


axiossessioncors Share Tweet +1