티스토리 뷰

Spring Boot

springBoot + React 데이터 전송

svdjcuwg4638 2023. 7. 25. 16:01

react에서 입력받은 데이터를 springBoot로 넘겨보자

 

react의 Signup.js

import axios from "axios";
import React, { useState } from "react";
import { Button, Form } from "react-bootstrap";

const Signup = () => {

 // form의 변경된점을 저장하기위한 state
  const [form,setForm] = useState({email:"",password:"",name:"",gender:""})

 // form안의 입력 데이터가 변경될때마다 발동되어 값을 실시간으로 바꿔줌
  const handleChange = (e) =>{
    setForm({
      ...form,
      [e.target.name]:e.target.value,
      입력된곳의 key값 : 입력된 값
    })
  }

  const submitForm = async (e) =>{
    e.preventDefault()
    try{
      const response = await axios.post('http://localhost:8081/signup',form)
      // axios로 spring에 요청을 보냄
      console.log('성공',response.data);
    }catch(error){
      console.log('에러발생',error);
    }
  }

  return (
    <div className="signup_wrap">
      <Form className="signup_inputBox" onSubmit={submitForm}>
        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>ID</Form.Label>
          <Form.Control type="text" name="userId" placeholder="아이디 입력" value={form.userId} onChange={handleChange} />
        </Form.Group>

        <Form.Group className="mb-3" controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control type="password" name="password" placeholder="비밀번호 입력" value={form.password} onChange={handleChange}/>
        </Form.Group>

        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>이름</Form.Label>
          <Form.Control type="text" name="name" placeholder="이름 입력" value={form.name} onChange={handleChange}/>
        </Form.Group>

        <Form.Label>성별</Form.Label>
        <Form.Select aria-label="Default select example" name="gender" value={form.gender} onChange={handleChange}>
          <option>성별</option>
          <option value="man">남</option>
          <option value="girl">여</option>
        </Form.Select>

        <Button variant="primary" type="submit">
          Submit
        </Button>
      </Form>
    </div>
  );
};

export default Signup;

 

springBoot의 Authcontroller.java

package com.example.productPJ.web;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.example.productPJ.domain.user.User;

@Controller
public class AuthController {

	
	@PostMapping("/signup")
	public ResponseEntity<?> login(@RequestBody User user) {
		System.out.println(user.getName());
		return ResponseEntity.ok().build();
	}
	
}

 

crossOrigin으로 하나의 메서드를 지정하여 그메서드만 리엑트의 페이지에서 요청이 가능하도록 하는것은 비효율적이다 그리하여 내가만든 react의 요청을 모두 수용하도록 config.WebConfig.java 생성

 

Webconfig.java

package com.example.productPJ.config;

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{
// 허용을 도와줄 WebMvcConfigurer을 implements

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
		.allowedOrigins("http://localhost:3000")
		.allowedMethods("*")
		.allowedHeaders("*");
		
	}
	
}

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함