๐Ÿฅ TIP

[NodeJS] CORS Error ํ•ด๊ฒฐํ•˜๊ธฐ

Eun_zii 2023. 9. 22. 15:12

React๋กœ ๋งŒ๋“  ํ”„๋ก ํŠธ์—์„œ axios๋ฅผ ํ†ตํ•ด nodejs๋กœ ๋งŒ๋“  api๋ฅผ ์š”์ฒญํ–ˆ๋”๋‹ˆ CORS ์—๋Ÿฌ๊ฐ€ ๊ณ„์† ๋ฐœ์ƒํ–ˆ๋‹ค.

๋ถ„๋ช… url๋กœ ๋“ค์–ด๊ฐ€๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์ž˜ ๋ฐ›์•„์˜ค๋Š”๋ฐ, ์™œ axios๋ฅผ ํ†ตํ•ด์„œ ์š”์ฒญ์„ ํ•˜๊ฒŒ ๋˜๋ฉด ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š”์ง€ ..๐Ÿคฆ๐Ÿป‍โ™€๏ธ

 

Access to fetch at 'http://localhost:8080/test' from orgin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response servers your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

 

port 8080์œผ๋กœ ์š”์ฒญํ–ˆ๋Š”๋ฐ ์ž๊พธ ๋ฆฌ์•กํŠธ์˜ 3000์œผ๋กœ ์žก์•„์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๊ฑฐ ๊ฐ™์•˜๋‹ค.

 

๐Ÿ”† ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

ํ”„๋ก ํŠธ์—”๋“œ์—์„œ proxy ์„ค์ •์„ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์ง€๋งŒ,

์ข€ ๋” ์•ˆ์ „ํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ๋ฐฑ์—”๋“œ์—์„œ response header์— Access-Control-Allow-Origin ์„ค์ •์„ ํ•˜๊ธฐ๋กœ ํ–ˆ๋‹ค.

 

โœ… ํ•„์š”ํ•œ api์— res.header("Access-Control-Allow-Origin", "*"); ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ๋˜์ง€๋งŒ, ๋ชจ๋“  api์— ๋Œ€ํ•ด์„œ ์„ค์ •ํ•˜๊ณ  ์‹ถ์œผ๋ฉด ๋ชจ๋“ˆ์„ ์„ค์น˜ํ•ด์„œ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

 

๐Ÿ”† ๋ชจ๋“ˆ ์„ค์น˜ํ•ด์„œ ํ•ด๊ฒฐํ•˜๊ธฐ

  • ํ•ด๋‹น ํ”„๋กœ์ ํŠธ ํด๋”๋กœ ์ด๋™ํ•ด์„œ ์ปค๋งจ๋“œ ์‹คํ–‰
  • app.js(์ž์‹ ์ด ์‚ฌ์šฉํ•˜๋Š” ์‹œ์ž‘ ๋‹จ๊ณ„์˜ ํŒŒ์ผ)๋กœ ๋“ค์–ด๊ฐ€์„œ ์ปค๋งจ๋“œ ์‹คํ–‰
npm install --save cors

 

  • app.js(์ž์‹ ์ด ์‚ฌ์šฉํ•˜๋Š” ์‹œ์ž‘ ๋‹จ๊ณ„์˜ ํŒŒ์ผ)๋กœ ๋“ค์–ด๊ฐ€์„œ
const cors = require('cors')

let corsOptions = {
  origin: '*',      // ์ถœ์ฒ˜ ํ—ˆ์šฉ ์˜ต์…˜
  credential: true, // ์‚ฌ์šฉ์ž ์ธ์ฆ์ด ํ•„์š”ํ•œ ๋ฆฌ์†Œ์Šค(์ฟ ํ‚ค ๋“ฑ) ์ ‘๊ทผ
}

app.use(cors(corsOptions))

๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

 

728x90