지영이의 개발 블로그

(2)서버에 GET 요청 하기,부트스트랩,Nodemon 본문

Node.js

(2)서버에 GET 요청 하기,부트스트랩,Nodemon

이지영 2022. 6. 4. 14:08

<서버를 띄우기 위해 작성할 기본 템플릿>

(server.js 파일)

const express = require('express');
const app = express();

app.listen(8080, function() {
    console.log('listening on 8080')
})

=> 위에 두줄은 express 라이브러리 첨부와 사용,

밑에 app.listen()은 원하는 포트에 서버를 오픈하는 문법

 

listen() 함수 안엔 두개의 파라미터가 필요합니다.

listen(서버를 오픈할 포트번호, function(){서버 오픈시 실행할 코드})

 

 브라우저에 localhost:8080 이라고 접속하면 확인가. 

 

app.get('/pet', function(요청, 응답) { 
  응답.send('펫용품 사시오')
})

=>그럼 누군가 우리 서버의 /pet 경로로 접속하면 '펫용품 사세요' 라는 안내메세지를 띄워주는 서버

 

 

GET 요청시 HTML 파일 보내기

누군가 /pet 방문시 HTML 파일을 보내주도록 합시다. 

(server.js랑 같은 폴더에 index.html 생성 후 작성)

<!DOCTYPE html>
  <html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  </head>
  <body>
    <h4>안녕하세요 홈페이지입니다.</h4>
  </body>
</html>
(server.js)

app.get('/', function(요청, 응답) { 
  응답.sendFile(__dirname +'/index.html')
});

=>- sendFile() 함수를 쓰면 파일을 보낼 수 있습니다

- __dirname은 현재 파일의 경로를 뜻합니다.

 

<자바스크립트에서 부트스트랩 설치하기>

구글에 Bootstrap 검색하신 후 맨 처음에 뜨는 사이트에 방문하도록 합니다.

그리고 Get started 메뉴 혹은 버튼을 누른 뒤

starter template라는 부분의 예제 코드를

 index.html 에 있던 내용을 삭제하고 붙여넣습니다.

https://getbootstrap.com/docs/4.4/getting-started/introduction/#starter-template

 

Introduction

Get started with Bootstrap, the world’s most popular framework for building responsive, mobile-first sites, with jsDelivr and a template starter page.

getbootstrap.com

 

 

<Nodemon설치법> 

Nodemon은 서버자동화 기능임

npm install -g nodemon 입력

 


서버실행 : nodemon server.js 

 

Comments