반응형

해당 내용은 개발자 본인이 다음에 node.js를 할때 어떻게 시작하는지 다시 보려고 작성한 글으로, 시작하는 방법만 작성

 

 

1. node.js 설치

Node.js 공식 사이트 에서 다운로드 받음

 

이미 설치되어있는지 확인하는 방법은 cmd창에서 node -v와 npm -v로 확인 가능하다. 

(npm도 일반적으로 node.js 설치시 같이 설치된다)

 

2. Node.js, express 세팅

2-1. cmd에서 원하는 디렉토리로 이동 후 npm init -y로 package.json 생성 (추후 수정 가능)

2-2. npm install express로 express 사용 (node_module폴더와 pacakge-lock.json 생성

2-3. index.js 라는 파일을 만들고, 해당 파일을 다음과 같이 작성

// index.js
const express = require('express'); 
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`서버가 http://localhost:${port} 에서 실행 중`);
});

2-4. node index.js 로 실행

2-5. localhost:3000으로 웹페이지에서 접속-> Hello World!를 볼 수 있음.

 

3. api 작성 방법 (다른 라우트 작성)

app.get('/api', (req, res) => {
  res.json({ message: 'API endpoint' });
});

index.js에 다음과 같이 작성 후, localhost:3000/api로 접속하면 다음 json을 받을 수 있다.

4. 짤막한 팁

4-1. npm start로 서버가 돌아가게 하기

package.json에 script부분을 다음과 같이 수정

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },

이제 npm start로도 실행이 가능하다.

 

5. 다음 단계

HTTP Method(get, post, put, delete)

웹서버를 github에 올리기

웹서버와 front를 연결하기

웹서버와 database를 연결하기

웹서버 AWS 배포

반응형

+ Recent posts