Vue

[Vue] Vue에서 Spring boot랑 연동하기

JH..Y 2021. 12. 24. 14:13
728x90

1. 필자는 axios를 사용하여 Spring boot랑 통신한다!

 

VSCODE에서 기본적인 Node및 Vue(필자의 Vue 버전 = @vue/cli 4.5.15)는 설치되있는 상태이고,

axios는 터미널 창에서 npm install axios입력하여 설치하였다.

 

2. vue create <project-name>을 터미널에 입력하여 project를 만들면 main.js파일이 생기는데 main.js파일을 axios 사용을 위해 아래코드처럼 조금 수정하였다.

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios';

axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.get['Content-Type'] = 'application/json;charset=utf-8';

const app = createApp(App)
app.config.globalProperties.axios = axios;
app.mount('#app')

3. vue create를 이용하여 만든 project의 폴더에다가 .env파일을 만들고 아래처럼 spring boot url 기본정보를 등록해주었다.

// vue port
PORT=8087
// spring boot 연동할 baseUrl
VUE_APP_baseApiURL = http://localhost:8883/point

4. 이제 src폴더 안의 App.vue파일에서 간단하게 <template>에 버튼을 만들고 이벤트를 주어 <script>에서 axios를 통해 spring boot랑 통신해보자!

[App.vue]

<template>
<div>
  ... 생략
  <div class="menu2" v-for="(상품,i) in 종합" :key="i">
	... 생략
    <button @click="getBackEndGo(i)">Get결과출력</button><br>
    <button @click="postBackEndGo(i)">Post결과출력</button>
  </div>
  <div>
      {{리턴}}
  </div>
</div>
</template>

<script>

export default {
  name: 'App',
  data(){
    return {
      리턴 : ''
    }
  },
  methods: {
    getBackEndGo(i){
      let url  = process.env.VUE_APP_baseApiURL + '/vueGet/' + i;
      console.log(url);
      this.axios.get(url)
        .then(function (response) {
          let result = response.data;
          console.log(result);
          return alert(result)
        })
        .catch(function (ex) { 
          console.log('getBackEndGo 실패', ex); 
        });
    }

    ,postBackEndGo(i){
      let params = {
        vueId : i,
        ... 생략
      };
      let url  = process.env.VUE_APP_baseApiURL + '/vuePost'
      console.log(url);
      console.log(params);
      this.axios.post(url, params)
        .then(res => {
          console.log(res.data);
          let result = res.data;
          console.log(result);
          return this.리턴 = result;
        })
        .catch(ex => { 
          console.log('postBackEndGo 실패', ex); 
        })
    }
  },

  components: {
  }
}
</script>

<style>
... 생략
</style>

 

[SpringBoot(controller)]

@RequestMapping("/point")
@RestController
@Slf4j
public class pointController {
	@GetMapping("/vueGet/{vueNumber:.+}")
	@ResponseBody
	public String vueGet(@PathVariable("vueNumber") String vueNumber) {
		log.info("GET 인입 : {}", vueNumber);
		String result = String.format("[GET] 결과값 리턴 : %s", vueNumber);
		return result;
	}
	
	@PostMapping("/vuePost")
	@ResponseBody
	public String vuePost(@RequestBody VueModel vueModel) {
		log.info("POST 인입 : {}", ToStringBuilder.reflectionToString(vueModel, ToStringStyle.MULTI_LINE_STYLE));
		String result = String.format("[POST] 결과값 리턴 : %s / %s / %s", vueModel.getVueId(), vueModel.getVueName(), vueModel.getVueCount());
		return result;
	}
}

 

5. 이제 Vue와 spring boot서버를 키고 실제로 연동이 되고있는지 확인해보자!

spring boot와 Vue서버켰다 !!

Vue Url(http:localhost:8087/)을 눌러 페이지를 키고 버튼을 클릭하여 Vue와 Spring boot가 통신이 잘 되는지 확인해보자!

 

 

Vue Axios를 이용하여 Spring boot랑 통신 성공!!

 

Get결과출력 버튼 클릭시 정상처리시의 Alert도 잘 떳다!

 

Vue axios 통신하던중 다른 포트 및 Url 요청시 console창에서 cors에러를 자주 볼 수 있는데 필자가 해결한 방식은 다음 포스팅에 정리하겠다!

 

 

728x90

'Vue' 카테고리의 다른 글

[Vue] Spring boot 연동시 cors 에러 해결  (0) 2021.12.25