ExpressJS 및 Heroku로 더미 API를 만들고 배포하는 방법
이를 위해 ExpressJS 서버를 만들고 GitHub 저장소에서 Heroku에 배포할 것입니다.
만약 질문이 있다면
나도 차근차근 만들어봤다video
GitHub 파일: https://github.com/dom-the-dev/doms-api
데모: https://doms-api.herokuapp.com/posts
내용 목록
노드JS
Before we yout can start you have to make sure that you have node
installed on your machine. To do so open your terminal and run following command:
node --version
v14.16.0
node is already installed. If not you need to install it. For that visit the https://nodejs.org/en/ 다운로드 및 설치가 가능한 곳.노드가 설치되면 시작할 수 있습니다.
설정 애플리케이션
In our terminal, let's create a new directory for our application with following command:
mkdir dummy-api && cd dummy-pi
Now we need to initialize npm. The following command will generate a package.json with defaults set.
npm init -y
After that we can add the ExpressJS framework with by running this command:
npm install express --save
Our project is now ready and we can open it in our favorite texteditor.
서버 생성
If you open package.json
you see that our main entry point is set to index.js.
"main": "index.js",
This means we need to name our server file exactly like that.
This is just a default value and you can rename it if you want to.
So, in our project root create a file index.js
which will be our application.
Here we can now create our server. To do so we need to require express.
const express = require('express')
To create our server we need to call express and store it in a variable like that:`
js
const app = express()
To actually make our server run we now need to run the listen method. Here we need to pass a port, on which the server will run. We also can pass a callback method.
js
app.listen(process.env.PORT || 3000, () => console.log("Server is running."))
Your server is ready to run. In your terminal run
cli
node index.js
to start your server.
`
The terminal should reponse with our callback function and you should see
cli
Server is running.
Now when you visit http:localhost:3000
you should get an error, since we are not responding to the browser.
Lets add that now.
We need to create a GET Route which will send a response to the browser.
js
app.get('/', (req, res) => {
res.send('Api is running.')
})
We create a new GET route by calling the app.get() function. Here we pass the path of the route as well as a callback function, which sends our response.
To make the changes affect you need to restart the server.
Then go back to your browser and reload the page.
You should now see Api is running.
in your browser.
더미 데이터 생성
To generate the dummy data, which we later want to serve on our API, we can use the json-generator which you find here.
On the left side you see the settings for you dummy data. You can play around and edit them like you want. If you want to dive deeper into that i recommend to check out the help section.
For our case it is enough to hit de generate button, and copy the generated JSON Object on the right side.
Now we need to store this JSON object in a file, so we can require it in our server application.
In the root of our project create a file named posts.js
. 다음과 같이 더미 데이터를 내보내려는 경우 내부:
js
module.exports = "paste your dummy data here"
JSON 응답
Move back to index.js
여기서 더미 데이터를 가져옵니다. 맨 위에 다음 줄을 추가합니다.
js
const posts = require("./posts");
Now we need to add another GET route similar to the first one, but instead of sending a simple response, we want to response with our json object.
Create a new GET route which points to /posts
더미 데이터 개체를 전달하는 json에 응답합니다.
js
app.get('/posts', (req, res) => {
res.json(posts)
})
GitHub 저장소
Our server is now ready to go, create a GitHub Repository where we can push the files to, so we can use them in our Heroku application.
Create a new repository on GitHub.
cli
git init
git remote add origin YOUR_GIT_URL
git add *
git commit -m "initial commit"
git push -u origin main
Heroku 앱 만들기
Create an account in Heroku and login to you dashboard.
On you app dashaboard create a new application by clicking on the button on the top right corner. Give your application a name, select a region an click on creat.
You will be redirected to the Deploy Tab. Here you can choose from several deployment methods. We are going to choose the GitHub method.
For that you need to connect your GitHub Account to Heroku. One this is done, you can browse your repositories. Here you can choose your Express Server Repository.
Now you can choose if you want to automatically deploy when you push to your main branch and you can deploy your application by clicking on the deploy branch button.
Before we can deploy our application we need to add one more thing.
프로필 추가
To let Heroku now which commands are needed to make our application run, we need to add a Procfile.
This Procfile contains the command which is needed to make our application run on Heroku.
Open your terminal an cd into your project root. Run following command to create this file:
cli
echo "web: node index.js"
Now push this file to your main branch.
서버 배포
The last step now is to accutally click on the Deploy Branch
.
그러면 배포 파이프라인이 실행됩니다. 여기에서 진행 상황을 확인할 수 있습니다.
이 작업이 완료되면 애플리케이션이 배포되었다는 성공 메시지가 표시되고 방문 버튼이 표시됩니다.
이제 ExpressJS 더미 데이터 API를 방문할 수 있습니다.
읽어 주셔서 감사합니다! 이 기사가 마음에 드셨으면 합니다. 피드백을 남겨주세요! :)
단계별 비디오
Reference
이 문제에 관하여(ExpressJS 및 Heroku로 더미 API를 만들고 배포하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/dom_the_dev/how-to-create-and-deploy-a-dummy-api-with-expressjs-and-heroku-4df3텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)