Axios POST 요청하는 간단 버튼 만들기

mcyoo.log·2022년 7월 30일
0

react

목록 보기
2/2
post-thumbnail

요약
react axios 를 이용하여 이메일 등록을 구현하고, AWS 로 배포하여 웹 접속 확인

구성도
/reactbutton 로 접속 요청 → nginx : 80 번 포트 → nginx : 443 포트 및 https 연결 → React Build 파일 전송

기술 스택
1. certbot(SSL 인증서 발급)
2. react(axios)
3. tailwindcss
4. aws ec2(Ubuntu), route53
5. nginx

초기 셋팅

node -v
npm -v

npx 설치
npm install npx -g
npx create-react-app react-button
//react-button 는 파일이름으로 react app 생성

cd react-button //이동
npm start // 시작 자동 웹창 뜸 초기 셋팅 완료

github에 코드 업로드

git init
git remote add origin {git URL}
git add .
git commit -m "{문구}"
git push origin master

패키지 설치

npm install axios //axios 설치

tailwindcss 설치

npm install tailwindcss postcss-cli autoprefixer -D 
npx tailwind init tailwind.js --full
npm install postcss


**tailwind.config.js //파일 생성**
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

**postcss.config.js //파일 생성**
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};

**src/assets/tailwind.css //파일 생성**
@tailwind base;
@tailwind components;
@tailwind utilities;

**src/assets/main.css //파일만 생성**

**package.json //내용 수정**
...
"scripts": {
    "start": "npm run watch:css && react-scripts start",
    "build": "npm run build:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:css": "postcss src/assets/tailwind.css -o src/assets/main.css", 
    "watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"
},
...

**index.js //내용 추가**
import React from "react";
import ReactDOM from "react-dom";
import './assets/main.css'; **<- 추가**
import App from "./App";
...

npm start 로 확인!

리액트 버튼 코드(src/App.js)

import React from "react";
import axios from "axios";

class App extends React.Component {
  state = {
    isLoading: false,
    error: false,
    email: "",
    result: "",
    message: "",
  };

  onInputValChange = (e) => {
    this.setState({ email: e.target.value });
  };

  postEmail = async () => {
    this.setState({ isLoading: true });

    await axios
      .post(
        "https://{post 요청 url}/email",
        {
          email: this.state.email,
        },
        {
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
          },
        }
      )
      .then((response) => {
        this.setState({
          message: "이메일을 확인해주세요.",
          error: false,
        });
        console.log(response.data);
      })
      .catch((response) => {
        this.setState({
          message: response.response.data.validation.email,
          error: true,
        });
      });

    this.setState({ isLoading: false });
  };

  componentDidMount() {}

  render() {
    const { isLoading, message, error } = this.state;
    return (
      <div className="container mx-auto px-4 py-14 sm:px-6 xl:px-12">
        <div className="flex items-center justify-center text-center">
          <input
            type="email"
            required={true}
            className="w-2/3 rounded-md border bg-gray-50 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-50"
            placeholder="you@website.com"
            onChange={this.onInputValChange}
          />
          {isLoading ? (
            <button
              className="w-1/3 rounded-md border border-blue-500 bg-blue-500 py-2 text-white text-center font-bold"
              disabled
            >
              <svg
                aria-hidden="true"
                className="w-6 h-6 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600 inline-block"
                viewBox="0 0 100 101"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                  fill="currentColor"
                />
                <path
                  d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                  fill="currentFill"
                />
              </svg>
            </button>
          ) : (
            <button
              onClick={this.postEmail}
              className="w-1/3 rounded-md border border-blue-500 bg-blue-500 py-2 px-6 text-white font-bold"
            >
              Submit
            </button>
          )}
        </div>
        {error ? (
          <span className="ml-2 text-sm text-red-500">{message}</span>
        ) : (
          <span className="ml-2 text-sm text-blue-500">{message}</span>
        )}
      </div>
    );
  }
}
export default App;

디자인

코드설명
axios json 형태로 서버에 post 요청 -> 서버는 해당 json 값에 따라 메세지 응답
-> 서버로 부터 응답 받은 메세지 state 값 업데이트 및 표시

package.json 내용 추가

{
  "name": "react-button",
  "version": "0.1.0",
  "private": true,
  "homepage": ".", <- 추가
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "axios": "^0.27.2",
    "postcss": "^8.4.14",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.0"
  },
...

배포

git add.
git commit -m "{문구}"
git push origin master

ec2 서버 접속

ssh -i "{ssh 접속용 키 파일}.pem" {aws url}

cd temp

rm -rf react-button

git clone {git url}

cp -rf react-button/* ../react-button/ // <- 덮어쓰기

cd ../react-button

yarn run build —prod //빌드

인증서 생성


certbot 설치

yum install certbot
certbot certonly --standalone 으로 도메인 입력 후 인증서 생성

인증서 생성 확인

/etc/letsencrypt/live/{도메인 이름}/fullchain.pem;
/etc/letsencrypt/live/{도메인 이름}/privkey.pem;

nginx 설정

server {
  listen 80;
  server_name  {도메인 이름};
  return 301 https://$server_name$request_uri;
}
server {
    listen       443 default_server ssl;
    server_name  {도메인 이름};

    ssl_certificate      /etc/letsencrypt/live/{도메인 이름}/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/{도메인 이름}/privkey.pem;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

	  location /reactbutton/ {
	     alias /home/ubuntu/react-button/build/;
	     index index.html index.htm;
	     try_files $uri $uri/ /index.html;
   }
}

sudo service nginx restart

해당 도메인으로 접속 확인 및 https 확인

정리
1. React axios 활용하여 유저가 입력한 이메일을 서버로 post 요청하는 간단한 웹사이트 구현을 했다.

0개의 댓글