๐Ÿ›  CORS ๋„๋ฉ”์ธ ๋ฌธ์ œ ํ•ด๊ฒฐ

๊ฐ•๋ƒ‰์ดยท2021๋…„ 1์›” 8์ผ
0

vuejs

๋ชฉ๋ก ๋ณด๊ธฐ
1/4

VueJS์—์„œ axios๋ฅผ ํ™œ์šฉํ•˜์—ฌ get๋ฐฉ์‹์œผ๋กœ api๋ฅผ ๋ฐ›์•„์˜ค๋ ค๊ณ  ์‹œ๋„ํ–ˆ๋Š”๋ฐ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

// console
Access to XMLHttpRequest at 'http://open.ev.or.kr:8080/openapi/services/EvCharger/getChargerInfo?serviceKey=0ZgyPnMBptn91BSdo5JXU4jvYNYB7puUnQzkXKP81T9PY67NeKiuOgIn%2baQmDk8zPmd9yhslatMa%2b7OGZFsEaw%3d%3d' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Api.vue?379d:22

Error: Network Error
    at createError (createError.js?2d83:16)
    at XMLHttpRequest.handleError (xhr.js?b50d:84)
xhr.js?b50d:177

GET http://open.ev.or.kr:8080/openapi/services/EvCharger/getChargerInfo?serviceKey=0ZgyPnMBptn91BSdo5JXU4jvYNYB7puUnQzkXKP81T9PY67NeKiuOgIn%2baQmDk8zPmd9yhslatMa%2b7OGZFsEaw%3d%3d net::ERR_FAILED

์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

๐Ÿง ์ผ๋‹จ ์ด ๋ฌธ์ œ๊ฐ€ ์™œ ๋ฐœ์ƒํ–ˆ๋Š”์ง€๋ถ€ํ„ฐ ์•Œ์•„๋ณด๊ธฐ์œ„ํ•ด CORS๊ฐ€ ๋ฌด์—‡์ธ์ง€๋ถ€ํ„ฐ ๋ณด์ž๋ฉด,,
CORS(Cross Origin Resource Sharing)๋ž€ ๋„๋ฉ”์ธ๊ณผ ํฌํŠธ๊ฐ€ ๋‹ค๋ฅธ ์„œ๋ฒ„๋กœ client๊ฐ€ ์š”์ฒญํ–ˆ์„๋•Œ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ๋ณด์•ˆ์ƒ ์ด์œ ๋กœ API๋ฅผ ์ฐจ๋‹จํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด client๋Š” 8080ํฌํŠธ๋กœ, server๋Š” 9000ํฌํŠธ์ผ๋•Œ, ๋˜๋Š” ๋กœ์ปฌ์—์„œ ๋‹ค๋ฅธ์„œ๋ฒ„๋กœ ํ˜ธ์ถœํ• ๋•Œ ๋ฐœ์ƒํ•œ๋‹ค. (๋‚˜์˜ ๊ฒฝ์šฐ๋Š” ํ›„์ž์˜ ๊ฒฝ์šฐ๋กœ ์˜ˆ์ƒ๋œ๋‹ค)

์ฆ‰, ๊ฐ„๋‹จํ•˜๊ฒŒ ๋™์ผ์ถœ์ฒ˜ ์ •์ฑ…์œผ๋กœ ๊ฐ™์€ ๋„๋ฉ”์ธ์ด ์•„๋‹ˆ๋ฉด ๋ฐ›๋Š” server์—์„œ ๋ชจ๋“  client ์š”์ฒญ์— ๋Œ€ํ•œ cross-origin HTTP๋ฅผ ํ—ˆ๊ฐ€ํ•ด์ฃผ์ง€ ์•Š๋Š”๋‹ค๋ฉด ๋ธŒ๋ผ์šฐ์ €๋‹จ์—์„œ ์œ„์™€ ๊ฐ™์€ cors์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

ํ˜„์žฌ, ๋‚ด๊ฐ€ ์š”์ฒญ๋ฐ›๋Š” server๋ฅผ ์ปจํŠธ๋กคํ• ์ˆ˜๋Š” ์—†๊ณ  ๋ฐฑ๋‹จ์—†์ด ํ”„๋ก ํŠธ๋‹จ(Vuejs)๋งŒ ์‚ฌ์šฉํ•˜๊ณ ์žˆ๋‹ค.
๊ทธ๋ ‡๊ธฐ๋•Œ๋ฌธ์— ์š”์ฒญ๋ฐ›๋Š” server์—์„œ ๋ชจ๋“  ์š”์ฒญ์„ ํ—ˆ๊ฐ€ํ•œ๋‹ค๋˜์ง€ ๋ฐฑ๋‹จ์—์„œ cors ํŒจํ‚ค์ง€๋ฅผ ์„ค์น˜ํ•ด์„œ ๋ฏธ๋“ค์›จ์–ด๋กœ ์ฒ˜๋ฆฌ๋ฅผ ํ•œ๋‹ค๋˜์ง€์˜ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ํ•ด๊ฒฐํ•  ์ˆ˜๊ฐ€ ์—†๋‹ค.

๐Ÿ” ํ•œ์ฐธ ๊ฒ€์ƒ‰ํ•˜๋‹ค๊ฐ€ ์•„๋ž˜์˜ ๋ธ”๋กœ๊ทธ๋“ค์„ ํ†ตํ•ด ํ•ด๊ฒฐ๋ฐฉ๋ฒ•์„ ์ฐพ์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

https://genie247.tistory.com/116
https://b1tblog.com/2019/11/03/vue-axios/ (์ผ์–ด ๋ฒˆ์—ญ ํ•„์š”)

์œ„ ๋‘๊ฐœ์˜ ๋ธ”๋กœ๊ทธ๋ฅผ ๋ณด๋ฉด, ๊ณตํ†ต์ ์œผ๋กœ ํ”„๋ก์‹œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๊ฒฐ๋ฒ•์„ ์ œ์‹œํ•ด์ฃผ๊ณ  ์žˆ๋‹ค.

  1. Vue์˜ ๊ฒฝ์šฐ, ๋ฃจํŠธ ๋””๋ ‰ํ† ๋ฆฌ์— vue.config.js ๋ผ๋Š” ํŒŒ์ผ์„ ๋งŒ๋“ค๊ณ  ๊ทธ ์•ˆ์— ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค. (๋ฃจํŠธ ๋„๋ฉ”์ธ๋งŒ ์ ๋Š”๋‹ค)
module.exports = {
  devServer: {
    proxy: 'http://open.ev.or.kr:8080'
  }
};
  1. server์— ์š”์ฒญํ•˜๋Š” url์„ ๋‹ค์Œ์™€ ๊ฐ™์ด ์ˆ˜์ •ํ•œ๋‹ค. (๋ฃจํŠธ ๋„๋ฉ”์ธ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€๋ฅผ ์ ๋Š”๋‹ค)
this.$axios.get(`/openapi/services/EvCharger/getChargerInfo?serviceKey=${DECODE_KEY}`)

์ดํ›„ ๋‹ค์‹œ ์‹คํ–‰ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๊ฒฐ๊ณผ๊ฐ’์„ ์ž˜ ๋ฐ›์•„์˜ค๋Š”๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€