찾아보게된 이유 🧐

Node.js 와 Express를 사용하여 백엔드 서버를 만들고

프론트엔드에서 Axios 를 활용하여 클라이언트 개발을 진행하는데

Postman 으로는 통신이 잘되지만 클라이언트에서는 호출이 안되는 현상

👉 ‘CORS’ 에러 발생
👉 ‘CORS’ policy 오류 CORS 정책을 위반할 때 발생
(교차 출처 리소스 공유(Cross-Origin Resource Sharing, CORS)

  • http://localhost:3000 (클라이언트)
  • http://localhost:8080 (서버)

Postman에서는 왜 ‘Cors’ 에러가 발생하지 않을까?

⭐ CORS 정책 위반 판단 검사를 시행하는 주체는 ‘브라우저’ 이다.
서버를 테스트하기 위해 Postman에서 요청을 실행할땐 문제없이 잘 동작하다가
서버를 실행하고 브라우저에서 통신을 하는 순간 ‘Cors’ 에러가 발생한다

원인은 바로 ‘브라우저’에 있다.
👉 그래서 브라우저 없이 서버 간 통신을 진행하는 Postman 에서는 ‘Cors’ 에러가 발생하지 않는다!


해결 방법 😎

JavaScript 를 이용할 경우 도메인과 포트가 동일해야한다
cors는 다른 origin 의 데이터를 불러오고 싶을 때
cors의 표준을 지켜 다른 origin 도 허용해주는 것이다

⭐ 보통은 서버(백엔드) 에서 해결해야하는 문제다

1. node.js 에서 ‘cors 미들웨어’ 추가 (성공한 방법)

1-1. npm install cors 명령어로 ‘cors’ 설치 (서버파일이 있는 경로에)

1-2. ‘cors’ 를 require 해주고 코드 추가

👆 코드 단 두줄만으로 에러를 해결할 수 있다 ❗


2. package.json 에서 proxy 설정 (실패한 방법)

2-1. axios 로 호출할 url의 호스트를 지우고
package.json에서 proxy 에 추가해준다

2-2. url의 호스트를 지우고 axios 로 다시 호출


3. http-proxy-middleware 라이브러리 (실패한 방법)

3-1. npm install http-proxy-middleware 명령어로 ‘proxy’ 미들웨어 설치

3-2. src 폴더 경로에 ‘setupProxy.js’ 파일 생성

3-3. createProxyMiddleware 코드 입력

const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    createProxyMiddleware({
      target: "http://localhost:8080",
      changeOrigin: true,
    })
  );
};

3-4. url의 호스트를 지우고 axios 로 다시 호출한다


참고 했던 사이트 🖥


발생했던 에러 내용

POST http://localhost:8080/ net::ERR_CONNECTION_RESET
POST http://localhost:8080/ net::ERR_FAILED
404 (Not Found)
Response {type: ‘basic’, url: ‘http://localhost:3000/’, redirected: false, status: 404, ok: false, …}
Uncaught Error: The error you provided does not contain a stack trace.
Uncaught (in promise) {message: ‘Network Error’, name: ‘AxiosError’, code: “ERR_NETWORK”, config: {…}, request: XMLHttpRequest, …} Access to XMLHttpRequest at ‘http://localhost:8080/’ 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. Uncaught (in promise) TypeError: Failed to fetch Uncaught ReferenceError: process is not defined
Uncaught Error: The error you provided does not contain a stack trace.