<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>jung-co.log</title>
        <link>https://velog.io/</link>
        <description></description>
        <lastBuildDate>Sat, 01 May 2021 06:07:15 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>jung-co.log</title>
            <url>https://images.velog.io/images/jung-co/profile/a0c8822d-abd6-4f8a-a746-7d077536fe97/social.png</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. jung-co.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/jung-co" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[Spring boot + React] Spring boot 와 React 연동하기]]></title>
            <link>https://velog.io/@jung-co/Spring-boot-%EC%99%80-React-%EC%97%B0%EB%8F%99%ED%95%98%EA%B8%B0</link>
            <guid>https://velog.io/@jung-co/Spring-boot-%EC%99%80-React-%EC%97%B0%EB%8F%99%ED%95%98%EA%B8%B0</guid>
            <pubDate>Sat, 01 May 2021 06:07:15 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p>개인적인 프로젝트로, 혹시 문제가 있다면 말씀해주세요 ! 😊</p>
</blockquote>
<h3 id="1-spring-boot-프로젝트-생성하기">1. Spring Boot 프로젝트 생성하기</h3>
<p><em>저는 <code>Gradle</code> 환경에서 진행했으나, <code>Maven</code>으로 진행해도 무관합니다.</em></p>
<p><img src="https://images.velog.io/images/jung-co/post/1c69be10-3943-488e-832e-f42e1ed1d169/new%20project.JPG" alt=""></p>
<p>🔨 여기서 <code>Spring Security</code>는 제외하고 선택해주세요 ! 이거 선택하면 화면 키자마자 로그인 화면이 먼저 떠버린다는 ,,,😅</p>
<p><img src="https://images.velog.io/images/jung-co/post/5c745b95-a670-44c5-a6f6-229d481f3327/new%20project2.JPG" alt=""></p>
<p>환경 설정 후, <strong>Finish</strong> !</p>
<p><img src="https://images.velog.io/images/jung-co/post/25143992-f58a-4b03-a197-a1dce69227ca/image.png" alt=""></p>
<p>짜잔 😎</p>
<h3 id="2-react-설치">2. React 설치</h3>
<pre><code>$ npx create-react-app front</code></pre><p><img src="https://images.velog.io/images/jung-co/post/8d7d24c6-500f-407c-a251-901486f070c9/image.png" alt=""></p>
<p>요렇게 <strong>Happy hacking</strong> 뜨면 완료 !</p>
<pre><code>$ cd front
$ npm start</code></pre><p>명령어로 <code>front</code> directory로 이동해서 실행해 보자</p>
<p><img src="https://images.velog.io/images/jung-co/post/d2626987-b2af-49c4-9e59-27672c3f9995/image.png" alt=""></p>
<p>이런 화면이 뜨면 설치 성공 😚</p>
<h3 id="3-spring-boot-실행">3. Spring Boot 실행</h3>
<p>클라이언트 요청을 받기 위한 <code>RestController</code> 작성 <a href="https://www.redhat.com/ko/topics/api/what-is-a-rest-api">RestAPI란?</a></p>
<pre><code class="language-java">package com.example.Controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @GetMapping(&quot;/home&quot;)
    public String getHome(){
        return &quot;Hello World!&quot;;
    }
}</code></pre>
<p><img src="https://images.velog.io/images/jung-co/post/6bfe67d2-9ac8-4fa4-9372-990d52ad19cb/image.png" alt=""></p>
<p><code>localhost:8080/home</code> 으로 이동했을 때 위 화면이 출력되면 성공 😀</p>
<h3 id="4-cors-해결">4. CORS 해결</h3>
<p>위에서 보면 <code>React</code>는 <code>3000</code> 포트, <code>Spring</code>은 <code>8080</code> 포트를 사용하면서 <code>CORS</code> 문제가 발생한다.</p>
<blockquote>
<p><strong>CORS(Cross-Origin Resource Sharing)</strong> 란 ? 추가 <code>HTTP</code> 헤더를 사용하여, <code>한 출처(origin)</code>에서 실행 중인 웹 애플리케이션이 <code>다른 출처(origin)</code>의 <code>선택한 자원에 접근할 수 있는 권한</code>을 부여하도록 브라우저에 알려주는 체제 <a href="https://developer.mozilla.org/ko/docs/Web/HTTP/CORS">(출처)</a></p>
</blockquote>
<p>이를 해결하기 위해서 <code>React</code>에서 <code>Proxy</code> 설정을 해준다. <a href="https://ko.javascript.info/proxy">Proxy란?</a></p>
<pre><code class="language-javascript">&quot;proxy&quot;: &quot;http://localhost:8080&quot;,</code></pre>
<p><code>front/package.json</code> 파일에 위 <code>Proxy</code> 설정 코드를 추가한다.</p>
<pre><code>추가 후에 [localhost:3000/home]으로 이동해도 
localhost:3000과 같은 페이지를 보여준다.
이는 React에서 화면을 렌더링해주는 App.js 가 변하지 않았기 때문이다.
화면에 Spring 정보를 보여주는 것은 이후에 작성할 예정이다.

따라서 화면이 아닌 curl 명령어로 REST 정보를 확인한다.</code></pre><pre><code class="language-java">$ curl localhost:3000/home
Hello World!</code></pre>
<p>위와 같이 정보가 출력되면 <code>Proxy</code> 설정 완료 !</p>
<h3 id="5-react-에서-spring-정보-불러오기">5. React 에서 Spring 정보 불러오기</h3>
<h4 id="1-axios-설치">1) axios 설치</h4>
<pre><code>$ npm i axios</code></pre><h4 id="2-appjs">2) App.js</h4>
<p><a href="https://joshua-dev-story.blogspot.com/2020/01/react-spring-2.html">여기</a>를 참고했습니다.</p>
<pre><code class="language-javascript">import React, { useState, useEffect } from &#39;react&#39;;
import axios from &#39;axios&#39;
import &#39;./App.css&#39;;

function App() {
  // 요청받은 정보를 담아줄 변수 선언
  const [ testStr, setTestStr ] = useState(&#39;&#39;);

  // 변수 초기화
  function callback(str) {
    setTestStr(str);
  }

  // 첫 번째 렌더링을 마친 후 실행
  useEffect(
      () =&gt; {
        axios({
            url: &#39;/home&#39;,
            method: &#39;GET&#39;
        }).then((res) =&gt; {
            callback(res.data);
        })
      }, []
  );

  return (
      &lt;div className=&quot;App&quot;&gt;
          &lt;header className=&quot;App-header&quot;&gt;
              {testStr}
          &lt;/header&gt;
      &lt;/div&gt;
  );
}

export default App;
</code></pre>
<p>💡 <code>useEffect</code> , <code>useState</code> 등에 대한 설명은 나중에 포스팅 하겠습니다 !</p>
<h4 id="3-실행">3) 실행</h4>
<p><img src="https://images.velog.io/images/jung-co/post/bba2fd81-96ec-4034-8f69-255eed2809f8/image.png" alt=""></p>
<p>실행했을 때, 위와 같은 화면이 나오면 성공 ! 🎉</p>
<ul>
<li>현재 <code>React</code> 를 처음 설치했을 때 같이 생성되는 <code>App.css</code>가 설정되어 있다. 따라서 <code>&lt;div&gt;</code> 태그와 <code>&lt;header&gt;</code>에 적용된 <code>className</code>을 지운다면 <code>css</code>가 적용되지 않아서 흰 화면에 <code>hello world</code>가 출력된다.</li>
</ul>
]]></description>
        </item>
    </channel>
</rss>