node 서버 만들기

웅평·2023년 7월 19일
0

서버 만들기

const http = require('http');

const server = http.createServer();

server.listen(3000);

서버역할을 하는 server객체를 만들고 listen를 통해서 server객체가 외부 요청을 받아들일 수 있게 한다. 3000은 포트번호이다.

위 코드는 무한로딩이 되고 서버로부터 응답이 오지 않는다. server객체가 클라이언트로부터 요청을 받았을 때 어떤 응답을 해줘야하는지 설정하지 않았다.

const http = require('http');

const server = http.createServer(function (request, response) {
  response.end('<h1>Hello World<h1>');
});

server.listen(3000);
response.end('<h1>Hello World<h1>')

를 통해서 클라이언트의 요청이 들어올 때마다 실행되는 함수다

request는 클라이언트의 요청에 관한 객체
response는 server 객체가 할 응답에 관한 객체이다

express모듈로 라우팅

설치

npm install express
const http = require('http');

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

const user = ['kim', 'you', 'lee']

app.get('/', (request, response) => {
  response.end('<h1>Welcome!</h1>');
});

app.get('/users', (request, response) => {
  response.end(`<h1>${users}</h1>`);
});

app.get('/users/:id', (request, response) => {
  const userName = users[request.params.id - 1];
  response.end(`<h1>${userName}</h1>`);
});

app.get('*', (request, respone) => {
  response.end(`<h1>준비중<h1>`);
});

app.listen(3000);

app이라는 객체의 get메소드를 써서 인자로 /, users 등 입력해준 path에 대해서 그 요청과 응답을 다루는 함수를 하나씩 설정하기 위해 쓰는 메소드

'/users/:id' 이런 path가 있는다 이 id는 이 위치에 오는 값을 id라는 속성에 담으라는 Express의 표기법이다.
이 id의 값은 request.params.id의 값이다

만약애 path에 관한 라우팅코드가 맨앞에 있다면 users로 이동해도 원하는 결과가 나오지 않고 path에 관한 결과가 나온다. 라우팅 코드를 쓸 때는 코드 상의 순서도 중요하다

참고
코드잇

0개의 댓글