반응형

평생 공짜로 쓸 수 있다고 해서 Oracle Freetier에 장비 하나를 구성해두었습니다. 

한참 잊고 지내고 있었는데, 그때 돌려놓았던 node 서버가 여전히 잘 돌아가고 있더군요.

 

이번엔 Oracle Freetier서버에 ExpressJS로 백엔드 서비스를 구성하고,

Netlify에 Jquery로 통신이 가능한 웹프로그램을 구성해 보았습니다.

 

1. Oracle Freetier

Cloud Free Tier | Oracle 대한민국

 

클라우드 서비스 무료 이용

Oracle Cloud Free Tier는 기업에게 무제한으로 사용할 수 있는 상시 무료 클라우드 서비스를 제공합니다.

www.oracle.com

 

[src/index.js]

간단하게 'Hello World'만 return하는 서버를 만들어 두었습니다. Github에서 해당 서버로 자동배포하는 것까지 구성은 못해서 FTP로 일일이 옮겨넣었습니다.

var express = require('express');
var app = express();
var user = require('./routes/user');

const cors = require('cors');
app.use(cors());

app.get('/', function (req, res) {	// 기본 root('/') 는 main.js에서 routing
    res.send('Hello World');
});

//app.use('/user', user);         	// 나머지 접근은 router(/routes/user)에서 routing


app.listen(3000, function () {   	// 3000 포트로 서버 실행
    console.log('Example App is listening on port 3000');
});

소스코드에 보시면, 다른 서버로부터의 요청이 허용되도록 app.use(cors())를 선언해줘야합니다.

위치는 라우팅보다 앞에 선언되어야 합니다.

 

2. Netlify

Scale & Ship Faster with a Composable Web Architecture | Netlify

 

Scale & Ship Faster with a Composable Web Architecture | Netlify

Realize the speed, agility and performance of a scalable, composable web architecture with Netlify. Explore the composable web platform now!

www.netlify.com

 

Netlify는 Github이나 Gitlab과 연동이 잘 되어 별도의 구성 없이도 CI/CD가 쉽게 가능합니다. 그래서 다른 Front Framework 사용하지 않고 html하고 jquery만으로 데이터를 받아오는 연습을 해봤습니다.

 

[index.html]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./js/jquery.min.js"></script>
</head>
<body>
 <div id="headline">Hello!!</div>
 <button onclick="ajax_request()">Ajax Request</button>
<script>
  function ajax_request(){
      $.ajax({
        url:'/api/', //'http://1xx.6xx.2xx.2xx:3000/', <- netlify에서 https요청으로 보내면, netlify.toml의 proxy설정을 통해 해당 서버로 요청됨
        method:'GET',
        async:false,
        success: function(data){
          console.log(data);
          document.getElementById('headline').innerText =data;
        }
      })
  }
 
</script>  
</body>
</html>

 

[netlify.toml]

[[redirects]]
  from = "/api/*"
  to = "http://1xx.6xx.2xx.2xx:3000/:splat"
  status = 200
  force = true

 

oracle 서버에서 cors 허용을 해놓았는데도 원래의 주소로 request를 보내면 오류가 납니다. 이유는 oracle에서는 http로 서비스를 하고 있고, netlify에서는 https로 서비스를 하고 있어서 그렇습니다. oracle에도 https서비스를 위한 인증서를 구해서 넣으면 좋지만, 위와 같이 proxy 우회 방법으로 간단히 두 서버간 통신이 가능합니다.

 

netlify에서는 ajax요청할 때, '/api/' 로 요청을 보내고,

netlify proxy설정을 통해 원래 서버로 전달됩니다.

 

 

그럼 이만~!

반응형

'Programming > ExpressJS' 카테고리의 다른 글

Node강좌 - 미들웨어  (0) 2020.08.09
Node강좌 - express 설치 / router설정  (0) 2020.08.09
반응형

서버리스 앱 만들기의 마지막 단원으로 Vue.js 프론트 앱을 배포해보도록 하겠습니다. 

 

1. 앱 만들기

Vue 앱을 만들어줍니다.

vue create node_post_vue .    // .을 찍으면 현재 폴더에 프로젝트를 생성합니다.

vue add router  // 곧바로 router 라이브러리를 함께 설치해줍니다.

 

필요한 라이브러리를 아래와 같이 설치해줍니다.

npm i vuex axios

간단히 백엔드에서 보내오는 데이터를 읽어다 표현해주는 것만 할건데도 Store를 구성하고 각 컴포넌트에서 Store state를 이용해야하는게 좀 불편해 보이네요. 그래도 한번만 세팅해놓으면 다음부터는 비교적? 편하게 작업을 할 수 있다고 생각하고 진행하셔요^^;;

 

 (1) ./src/main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store/store.js'

createApp(App)
.use(router)
.use(store)
.mount('#app')

 

(2) ./src/App.vue

<template>
  <router-view/>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

 

 (3) ./src/router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

 

  (4) ./src/components/HelloWorld.vue

<template>
  <div class="hello">    
    <ul>
      <li class="post" v-for="post in postlist" :key=post>
        <div class="title">
          {{ post.title }} 
        </div>
        <div class="content">
          {{ post.content }} 
        </div>
        <div class="lower">
          <div>...by {{ post.creator }} </div>
          <div>on {{ post.publish_date.split('T')[0] }}</div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script scoped>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  computed:{
    postlist(){            
      return this.$store.state.posts;
    },    
  },
  created(){
      this.$store.dispatch('onLoad');
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
ul {
  text-align: center;
  list-style-type: none;
  margin: 0 auto;
  padding: 0;
  width: 800px;
}
.post {
  /* display: inline-block; */
  margin: 10px 10px;  
  border: 1px solid #42b983;
  border-radius: 15px;
  padding: 8px;
}

.post .title{
  text-align: left;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  font-size:larger;
  font-weight: 900;
  color:#222;
}
.post .content{
  text-align: left;
  font-size:small;
  padding: 5px;
  height: 80px;
  color:#999;
}
.post .lower{
  text-align: right;
  color:grey;
  font-size:small
}
a {
  color: #42b983;
}
</style>

 

  (5) ./src/store/store.js

import { createStore } from 'vuex';
import axios from 'axios';

axios.defaults.baseURL = 'https://vmsahpyntz.eu10.qoddiapp.com';
axios.defaults.headers.post['Content-Type']='application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin']='*';

export const store = createStore({
  state:{
    posts:[]
  },
  mutations:{
    updateState(state, payload){
      Object.keys(payload).forEach((key) => {
        state[key] = payload[key];
      });
    }
  },
  actions:{
    async onLoad(context){
      const res= await axios.get('/');
      const post = res.data;
      // console.log(res);
      
      context.commit('updateState',{
        posts:[...context.state.posts, ...post],
      })
    },
  }
});

 

2. gitlab에 배포하기

저는 회사 특성상 github 접근이 불가능해서 gitlab을 주로 사용합니다. 사용 방법은 github과 동일합니다.

git remote add origin [gitlab주소: 대활호 빼고]
git pull origin main
git add .
git commit -m "initial commit"
git push origin main // main인지 master인지 본인의 branch를 잘 확인하고 진행합니다.

 

3. Netlify에서 연동하기

Netlify에 접속해줍니다. 계정이 없다면 적당한 방법으로 계정을 생성해주셔요.

"Sites  >  Add new site  >  Import an existing project"를 클릭해줍니다.

아래 그림에서 본인의 저장소가 있는 곳을 선택합니다. 저는 Gitlab

 

본인의 프로젝트를 선택합니다.

 

배포 세팅을 하게 되됩니다. 배포할 브랜치, 빌드 명령어(npm run build), 배포 디렉토리(일반적으로 /dist) 를 확인하고, 아래에 Deploy Site를 눌러주면 배포가 시작됩니다.

 

배포가 완료되면 아래와 같이 화면이 변경되며, 배포된 url이 표시가 됩니다. 

 

해당 링크를 클릭하면 우리가 만든 사이트가 나타납니다.

 

이제 수정사항이 생길때마다 Gitlab으로 배포만 하면 자동으로 Netlify도 업데이트됩니다. 

지금까지 DB, Backend 서버, Frontend 서버를 모두 서버리스로 구현해보았습니다.

 

~~~끝~~~~

반응형
반응형

1. 백엔드

헤로쿠에 백엔드를 배포할 경우 CORS(Cross Origin Resource Sharing) 문제를 해결하기 위해 라이브러리를 설치해야 합니다. Koa로 작업할 경우 'koa2-cors' 를 설치해주면 됩니다.

그리고 라우팅 설정 부분에서 아래의 구문을 추가해줍니다.

import cors from 'koa2-cors';

app.use(cors());

 

2. 프론트엔드

Github의 소스를 자동으로 배포해주는 Netlify의 경우에도 일부 수정할 부분이 필요합니다. Local에서 작업할 경우에는 같은 localhost에서 데이터를 주고 받아서 몰랐었는데, 이제 헤로쿠의 백엔드 데이터를 받아와야 하기 때문에 조금 달라져야 합니다. 그래서 필요한 것이 _redirects파일 입니다. /public 폴더에 _redirects라는 이름의 파일을 생성한 후 아래와 같이 작성해줍니다. 

/*  /index.html 200
/api/* https://헤로쿠앱이름.herokuapp.com/api/:splat  200

프론트엔드 화면에서 버튼이나 페이지 이동에 의해 서버 요청이 발생할 경우, url에 해당하는 경로를 적고, 그에 대응하는 실제 주소를 적어주면 됩니다. 뒤의 :splat은 *과 동일한 의미라고 합니다. 그리고 뒤의 숫자 200은 아직 잘 모르겠습니다. 정상 접속을 의미하는 200이라면 굳이 붙여야 하는지도 잘 모르겠고... 다른 숫자를 붙일 수도 있는데, 301은 url을 영구적으로 옮겼을 때 사용하고, 검색엔진 최적화에 좋다고 합니다. 302 일시적으로 옮겼을 때 사용한다고 합니다.

 

~끝~

반응형

+ Recent posts