JavaScript/nodeJS & Ajax & Plugin

node.js & Spring 서버 연동 / Put,Delete 통신 설정 / axios 호스트 주소 전역 등록 및 put 요청,응답 파라미터

유혁스쿨 2022. 12. 4. 21:30
728x90
반응형

[프론트서버 백앤드서버 CORS연동 설정]

 

axios 통신주소로 Spring의 url을 입력하여 프론트 서버와 백앤드 서버가 서로 통신하기 위해서는 백엔드 서버에서 CORS 를 설정해야한다.

Cors Mapping (Cross-Origin Resource Sharing,CORS) 이란 다른 출처의 자원을 공유할 수 있도록 설정하는 권한 체제를 말한다. 따라서 CORS를 설정해주지 않거나 제대로 설정하지 않은 경우, 원하는대로 리소스를 공유하지 못하게 된다.

 

아래와 같이 설정할 클래스를 만들어야하는데, 이때 WebMvcConfigurer 인터페이스를 구현받아야 한다.

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
    }
}

WebMvcConfugure 인터페이스에서 제공하는 addCorsMapping() 메소드를 Override하여 위 코드와 같이 선언하면 프론트 서버와 백엔드 사이의 기본적인 통신 연동 설정이 끝난다.

 

 

[CORS PUT,DELETE 메소드 ]

CORS 에러시 백엔드

CORS 설정에서 함께 설정해 줘야 한다.

아래와같이 allowedMethods() 메소드 매개변수 인자값에 허용할 메소드명을 입력한다. 

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods(
                    HttpMethod.GET.name(),
                    HttpMethod.HEAD.name(),
                    HttpMethod.POST.name(),
                    HttpMethod.PUT.name(),
                    HttpMethod.DELETE.name()
                );
    }
}

allowMethod를 추가할 경우 DEFAULT 설정이 사라지기 때문에 GET,HEAD,POST 또한 포함해 주어야 한다

 

 

[Axios DELETE 요청 파라미터 / Spring  파라미터 처리]

개발자 도구에서 네트워크 탭에서 페이로드를 확인해보면 {"" : ""}과 같은 형태로 찍혀있다.
필자는 고민끝에 JSON형태로 전송했으니 @RequestBody를 통해 Map 컬렉션 으로 파라미터를 처리하자고 결정.

 

    let url = 'http://localhost:8090/delete/${id}'
    let param = {
                 data:{
                       password : 1234
                      }
                }
            
    axios.delete(url,param)
    .then((response) => {
        alert(response.data);
    })
    .catch((error) => {
        alert("Error : ",error)
    })

axios에서는 위 코드와같이 delete 메소드를 사용할 때 파라미터를 data 객체를 활용하여 전송한다.

 

자바 Controller코드

@DeleteMapping("/delete/{id}")
public ResponseEntity<String> delete(@PathVariable Integer id
                                   , @RequestBody Map<String, String> data) {

    String password = data.get("password");
    ResponseEntity<Integer> res = null;
    try {
        res = new ResponseEntity<String>(password, HttpStatus.OK);
    } catch (Exception e) {
        res = new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    }
    return res;
    
}

@RequestBody로 Map<String,String> 타입의 data 변수에

axios Delete요청으로 부터 넘겨받은 JSON객체 형태인 data 파라미터를 받게된다.

 

 

 

[React 서버 포트 변경]

node.js에서 기본적으로 사용하는 포트번호는 3000이다.
Package.json 파일에서 "Scripts" 객체의 "Start" 속성에 아래와 같이 값을 추가하면 실행 서버 포트 변경이 가능하다.

"scripts": {
    //"start": "react-scripts start",
    "start": "set PORT=80 && react-scripts start",
    /* 생략 */
  },

 

 

[React axios 통신주소중 호스트 주소 전역 등록]

package.json에서 첫번째 객채 레벨에 "proxy":"http://localhost:80", 코드를 추가한다.

{
  "name": "openapiapp",
  "version": "0.1.0",
  "private": true,
  
  /*아래 코드를 추가*/
  "proxy":"http://localhost:80",
  
  "dependencies": {
    	/* 생략 */
  	},
  	"scripts": {
    	/* 생략 */
    }
}

 

728x90
반응형