No access-control-allow-origin header is present on the requested resource react fetch

let fetchSenators = () => { fetch('https://api.propublica.org/congress/v1/115/senate/members.json', { mode: 'cors', headers: { 'X-API-Key': 'Q82EAnyHuygomXxK2mNDfcHkvOQ17EmsBPvOc1eq' } }).then(response => response.json()) .then(response => { renderResults(response.results[0].members) })}

Show


No access-control-allow-origin header is present on the requested resource react fetch

이번 글을 통해 배워갈 내용

  1. CORS policy 문제를 해결하는 한 가지 방법

서론

후배가 도움이 필요해서

연락이 왔다

문제는 바로 학교 프로젝트에서

열린 데이터를 프론트 단에서 바로 가지고 와서 쓰고 싶은데

(아래는 열린 데이터 광장 주소)

https://data.seoul.go.kr/

열린데이터광장 메인

데이터분류,데이터검색,데이터활용

data.seoul.go.kr

No access-control-allow-origin header is present on the requested resource react fetch

아래와 같이 에러가 뜬다는 것이다.

"

Access to fetch at 'http://example.com/movies.json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

"

Access to fetch at 'http://example.com/movies.json' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

설명

이 문제를 설명하자면

CORS 정책 (Cross-Origin Resource Sharing Policy)을 위반했다는 것이다.

이를 쉽게 이야기 하면

출처가 다른 두 애플리케이션을 소통하려 하기 때문에

사용자의 공격에 취약해서

악의를 가진 사용자가 공격을 할 수 있기 때문에 미리 정책적으로 막아둔 것이다.

같은 주소로 판정되려면

Scheme, host, port가 동일해야 한다.

예시

http://www.nxver.com:8080

https://api.nxver.com:7777

간략하게 예시로 설명하자면

파란 게 Scheme

빨간 게 host

초록이 Port다.

상황

후배의 경우 상황이

fetch로 API 데이터를 가지고 와야 하는 경우였는데

예를 들어 아래와 같이 코드를 작성했는데

const fetch_url = "https:://주소" fetch(fetch_url, { method: "GET", headers: { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest", }, }) .then((response) => response.json()) .then((data) => { console.log(data); //처리작업 });

크롬 개발자 모드에서 확인을 해보니까

계속

has been blocked by CORS policy 가 나와서 매우 당황했고

결국 풀 스택 개발이 가능한 나에게 연락이 왔다.

나는 5분 만에 해결을 해주었고

친구는 너무 고마운 나머지 밥을 대접하겠다고 했으나

나는 그냥 괜찮다고 코로나 끝나면 같이 더치로 밥이나 먹자고 했다.

Cors Policy 5분 해결책

이문제의 근본적 해결방법은

No access-control-allow-origin header is present on the requested resource react fetch
Cors policy solution

위와 같이 파란선으로 외부 API 서버와 통신하는 상황을

주황선으로 바꿔서 백 단 서버를 하나 만들어서 CORS 정책에 맞게 바꿔서 유저에게 보내주면 해결된다.

5분 안에 해결이 안 된다 생각될 수 있지만

5분 아니 3분 안에 가능하다.

윈도를 기준으로 설명하겠다.

1. cmd를 연다

2. 원하는 폴더로 가서 디렉터리를 복사한다.

3. 아래와 같이 친다.

git clone https://github.com/Rob--W/cors-anywhere.git

cd cors-anywhere/

npm install

heroku create

git push heroku master

---------------------------------------------------

3번 방법을 하는데 node, npm 혹은 heroku가 없다면

만약 node, npm과 heroku 가 없다면

노드를 설치해주고

https://nodejs.org/

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

No access-control-allow-origin header is present on the requested resource react fetch

헤로쿠 설치방법

https://devcenter.heroku.com/articles/heroku-cli

The Heroku CLI | Heroku Dev Center

Last updated April 27, 2021 The Heroku Command Line Interface (CLI) makes it easy to create and manage your Heroku apps directly from the terminal. It’s an essential part of using Heroku. Download and install The Heroku CLI requires Git, the popular vers

devcenter.heroku.com

No access-control-allow-origin header is present on the requested resource react fetch

아래와 같이 npm과 heroku를 설치합니다.

npm install -g npm

npm install -g heroku

노드, npm, 헤로쿠 설치가 돼있는지 헷갈리신다면

node -v
npm -v
heroku --version

헤로쿠의 경우 회원가입도 필요합니다.

---------------------------------------------------

3번이 마무리되었다면

3번에서 받은 주소에

"주소" + "/ "+ "API 받고자 하는 원래 주소"로 해서

위에 fetch를 그대로 하면 정상 작동합니다.

적어도 저는 정상 작동했고 몇 달간 아무 문제없었습니다.

예(아래는 없는 주소입니다 예시용임)

https://floating-savannah-231232131.herokuapp.com/http://openapi.seoul.go.kr:8088/"

후배를 멘토링 해준 사이트도 정상 작동했습니다.

이로서 쉽게 공공데이터를 무료로 받아서 실시간으로 정보를 보여줄 수 있게 되었습니다.

이상입니다.

추가 정보를 원하시면

보실 수 있게 아래에 추가 정보 링크를 달아 두었습니다.

(API 서버에서 CORS를 열수있는 경우 혹은 CORS를 전부 막아둔 경우 위의 방법이 필요하지 않습니다) 


힘든 일이 있으시다면 한번 활짝 웃어보세요~

기분이 좋아집니다.

하하하 호호호

오늘도 즐거운 일만 가득 있으시길 바랍니다.

참조 및 인용

https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors/43268098

Trying to use fetch and pass in mode: no-cors

I can hit this endpoint, http://catfacts-api.appspot.com/api/facts?number=99 via Postman and it returns JSON Additionally I am using create-react-app and would like to avoid setting up any server ...

stackoverflow.com

No access-control-allow-origin header is present on the requested resource react fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Using Fetch - Web APIs | MDN

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across th

developer.mozilla.org

No access-control-allow-origin header is present on the requested resource react fetch

https://github.com/Rob--W/cors-anywhere/

GitHub - Rob--W/cors-anywhere: CORS Anywhere is a NodeJS reverse proxy which adds CORS headers to the proxied request.

CORS Anywhere is a NodeJS reverse proxy which adds CORS headers to the proxied request. - GitHub - Rob--W/cors-anywhere: CORS Anywhere is a NodeJS reverse proxy which adds CORS headers to the proxi...

github.com

No access-control-allow-origin header is present on the requested resource react fetch

https://codemasterkimc.tistory.com/50

300년차 개발자의 좋은 코드 5계명 (Clean Code)

이번 글을 통해 배워갈 내용  좋은 코드(Clean Code)를 작성하기 위해 개발자로서 생각해볼 5가지 요소를 알아보겠습니다. 개요 좋은 코드란 무엇일까요? 저는 자원이 한정적인 컴퓨터 세상에서 좋

codemasterkimc.tistory.com

No access-control-allow-origin header is present on the requested resource react fetch