[React] ์• ์ฆ์˜ CORS ... ๐Ÿดโ€โ˜ ๏ธ

uoayopยท2022๋…„ 2์›” 13์ผ
4

์—๋Ÿฌ ํ•œ๋ฐ”๊ฐ€์ง€

๋ชฉ๋ก ๋ณด๊ธฐ
16/16
post-thumbnail

์ƒํ™ฉ

์•ผ๋ฌด์ง€๊ฒŒ CORS๋ฅผ ๊ณต๋ถ€ํ•˜๊ณ  ๋ธ”๋กœ๊ทธ์— ์ •๋ฆฌํ–ˆ์ง€๋งŒ,,
์‹ค์ œ ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ CORS๊ฐ€ ๋ฐœ์ƒํ•˜๋‹ˆ๊นŒ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐ์— ํ•œ์ฐธ ๊ฑธ๋ ธ๋‹ค.


์—๋Ÿฌ ์ฝ”๋“œ

  • ์ด์   ๋„ˆ๋ฌด ๋งŽ์ด ๋ด์„œ ์™ธ์šธ ์ง€๊ฒฝ
Access to fetch at โ€˜http://localhost/8089/api/authโ€™ from origin โ€˜http://localhost:8080โ€™ has been blocked by CORS policy: 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.

๋ฐœ์ƒํ•˜๋Š” ์ด์œ 

์š”์ฒญ ์ถœ์ฒ˜ ๊ฐ€ ๋‹ฌ๋ผ์„œ ์ƒ๊ธด๋‹ค.

  • ์ถœ์ฒ˜๋ž€ URL์˜ ํ”„๋กœํ† ์ฝœ, ํ˜ธ์ŠคํŠธ, ํฌํŠธ

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

  • ํ”„๋ก ํŠธ์™€ ๋ฐฑ์—์„œ ๋ชจ๋‘ ์ฒ˜๋ฆฌํ•ด์ฃผ์—ˆ๋‹ค.

FrontEnd

  • axios๋กœ api๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ Access-Control-Allow-Origin์— ํ˜„์žฌ ํ”„๋ก ํŠธ์—”๋“œ ์ถœ์ฒ˜๋ฅผ,
    Access-Control-Allow-Credentials์—” true๋ฅผ ์„ค์ •ํ•ด์ฃผ์—ˆ๋‹ค.
// /pages/api/index.js

const getAuth = (token) => axios.create({
    baseURL: BASE_URL,
    headers: {
        "Content-Type": `application/json;charset=UTF-8`,
        "Accept": "application/json",
        "Authorization": "Bearer "+token,
      
        // ์ถ”๊ฐ€  
        "Access-Control-Allow-Origin": `http://localhost:3000`,
        'Access-Control-Allow-Credentials':"true",
    }
})

BackEnd

  • spring์— ์›น๊ณผ ๊ด€๋ จ๋œ ์„ค์ •์„ ํ•ด์ค€ config ํŒŒ์ผ์—
    addAllowedOrigin์œผ๋กœ ํ”„๋ก ํŠธ์—”๋“œ ์ถœ์ฒ˜๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ๋‹ค.
// WebMvcConfig.java

package com.ssafy.config;

import com.ssafy.common.util.JwtTokenUtil;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
       // ์ถ”๊ฐ€
       configuration.addAllowedOrigin("http://localhost:3000");
       ...
        
    }
}
profile
slow and steady wins the race ๐Ÿข

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