프로그래밍(Web)/Javascript(TS,Node)

[바미] React, Go(Gin) axios 통신 예제 코드.

Bami 2023. 1. 19. 16:32
728x90
반응형

React

import axios from "axios";
const api = axios.create({
  baseURL: "http://localhost:3000",
  // headers: { "Content-Type": "application/json" },
  withCredentials: true,
});
export const getData = async () => {
  await api
    .get("data")
    .then((response) => {
      if (response.ok) {
        return response.json();
      }
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error);
    });
};

function App() {
  const apiHandler = () => {
    getData();
  };
  return <button onClick={apiHandler}>버튼<button>;
}

export default App;

버튼 클릭 시 get으로 가져옵니다.

 

Go(Gin)

package main

import (
  "net/http"

  "github.com/gin-gonic/gin"
  "github.com/icrowley/fake"
)

type Data struct {
  ID   int    json:"id"
  Name string json:"name"
  Email string json:"email"
}



var dataList []Data

func main() {
  r := gin.Default()
  for i := 0; i < 10; i++ {
        dataList = append(dataList, Data{
            ID:    i,
            Name:  fake.FullName(),
            Email: fake.EmailAddress(),
        })
  }

  r.GET("/data", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      "data": dataList,
    })
  })

  r.POST("/data", func(c *gin.Context) {
    var data Data
    if err := c.ShouldBindJSON(&data); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }
    c.Status(http.StatusOK)
  })


  r.Use(CORSMiddleware())

  r.Run()
}

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }

        c.Next()
    }
}

 

728x90
반응형