본문 바로가기

기술 공부/Spring

spring boot & next http 통신 커넥트

반응형

controller

@RestController
@CrossOrigin
public class TestController {

    @GetMapping("/api/hello")
    public String testConnection() {
        System.out.println("연결");
        return "연결 성공";
    }
}

 

porxyConfig (CorsFilter 설정)

// http 통신 연결
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class proxyConfig implements WebMvcConfigurer {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("<http://localhost:3000>"); // 프론트엔드 애플리케이션의 도메인 및 포트번호
        // 다른 허용할 출처 패턴들을 추가

        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/api/**", config);

        return new CorsFilter(source);
    }
}

 

package.json

  "name": "user-projdct-name",
  "version": "0.1.0",
  "private": true,
  "proxy": "<http://localhost:8080>",

8080포트로 요청 보내기 설정

 

http 통신이 필요한 페이지에 axios 호출

    useEffect(() => {
        async function fetchData() {
            const response = await axios.get('<http://localhost:8080/api/hello>');
            console.log(response.data);
        }
        fetchData();
    }, []);

 

클라이언트 응답

 

서버 응답

 

DB연결 (application.yml 생성)

# JPA
spring:
  datasource:
    driver-class-name:
    url: ${SPRING_DATASOURCE_URL}
    username: root
    password: ${SPRING_DATASOURCE_PASSWORD}
  jpa:
    database: mysql
    database-platform: org.hibernate.dialect.MySQLDialect
    show-sql: true
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        format_sql: true

username, 또는 password, db url 등 하드 코딩 또는 환경 변수 설정해서 사용하면 된다.

 

 

DB연결 - build_gradle 추가

 implementation 'mysql:mysql-connector-java'
  implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

 

 

application.properties

SPRING_DATASOURCE_URL= 
SPRING_DATASOURCE_PASSWORD= 

 

 

인텔리제이 db 연결

반응형