Skip to content
spring학습 기록

Team project setup: Spring Boot + React with TypeScript

1 min readLearningMoved from my Tistory blogRead the Korean original

For our team's project, we decided to build the front end with React and TypeScript and plan the back end with Spring Boot.

The back-end members would use IntelliJ as their tool, and we decided the front end would use VS Code.

To set up the project, I first went to https://start.spring.io/.

Apart from when I watched 김영한's lectures before, it was my first time.

I think I filled it in like this, except for the Group name.

Then I downloaded the files with GENERATE.

After that, I set up the development environment by referring to the post at the link below.

https://velog.io/@u-nij/Spring-Boot-React.js-%EA%B0%9C%EB%B0%9C%ED%99%98%EA%B2%BD-%EC%84%B8%ED%8C%85

Connecting a Spring Boot + React.js development environment

One difference is that I didn't build the frontend files with CRA. I built them with Vite.

So I had created the frontend folder in VS Code beforehand, set up the whole working environment, and then pasted it under main.

Then, to prevent CORS errors, I set up a proxy.

First, I created a setProxy.js file in the src/main/frontend/src folder and pasted in the code below.

js
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(
        '/hello',
        createProxyMiddleware({
            target: 'http://localhost:8080',
    changeOrigin: true,
})
);
};

Now when the front end sends a request to '/hello', the request arrives at the back end on port 8080.

Then I cleared out src/main/frontend/src/App.tsx and put in the code below.

Before that, to use axios, you need to install it with the command below.

bash
npm install axios --save
jsx
import { useEffect, useState } from "react";
import axios from "axios";

function App() {
  const [hello, setHello] = useState("");

  useEffect(() => {
    axios
      .get("http://localhost:8080/hello")
      .then((response) => setHello(response.data));
  }, []);

  return <div>백엔드에서 가져온 데이터입니다! : {hello}</div>;
}

export default App;

Then, on the back end, I created a package called Controller under java/(package name), created a class file called HelloWorldController under it, and gave it the following content.

js
package team.compass.Controller;


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

@RestController
public class HelloWorldController {
    @GetMapping("/hello")
    public String test() {
        return "제로베이스 1석 4조 화이팅";
    }
}

After that, I did a few more things to prevent CORS errors. First, I put the following code into build.gradle.

ts
def frontendDir = "$projectDir/src/main/frontend"

sourceSets {
   main {
      resources { srcDirs = ["$projectDir/src/main/resources"]
      }
   }
}

processResources { dependsOn "copyReactBuildFiles" }

task installReact(type: Exec) {
   workingDir "$frontendDir"
   inputs.dir "$frontendDir"
   group = BasePlugin.BUILD_GROUP
   if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
      commandLine "npm.cmd", "audit", "fix"
      commandLine 'npm.cmd', 'install' }
   else {
      commandLine "npm", "audit", "fix" commandLine 'npm', 'install'
   }
}

task buildReact(type: Exec) {
   dependsOn "installReact"
   workingDir "$frontendDir"
   inputs.dir "$frontendDir"
   group = BasePlugin.BUILD_GROUP
   if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
      commandLine "npm.cmd", "run-script", "build"
   } else {
      commandLine "npm", "run-script", "build"
   }
}

task copyReactBuildFiles(type: Copy) {
   dependsOn "buildReact"
   from "$frontendDir/dist"
   into "$projectDir/src/main/resources/static"
}

Then I created WebConfig at the root of java/(package name), where CompassApplication is, and put in the content below.

js
package team.compass;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .maxAge(3600);
    }

    @Bean
    public WebConfig corsConfigurer() {
        return new WebConfig();
    }
}

I kept getting CORS errors until I added this part, and once I added it, they were cleanly resolved.

  • #React
  • #Vite
  • #Development Environment Setup
  • #Zerobase Frontend School

More in Learning