[Node.js] node 서버 연결

김민재·2024년 3월 29일

Node.js

목록 보기
20/36

기본적인 서버 연결

const http = require("http");

const port = 3000;

const server = http.createServer((req, res) => {
  if (req.url === "json") {
    res.writeHead(200, {
      "Contype-Type": "application/json",
    });
    res.end(JSON.stringify({ a: "a" }));
  } else {
    res.writeHead(200, {
      "Contype-Type": "text/plain",
    });
    res.end("HELLO WORLD");
  }
});

server.listen(port, () => {
  console.log("서버 연결 완료");
});
  • 위 예시는 HTTP만을 이용해서 서버를 실행하는 법이다. port는 3000번 포트를 연결 시킬 것이다.
  1. 터미널에서 node app.js를 실행하면 서버가 정상적으로 연결 된다.
  2. node 환경 터미널에서 console.log 찍힐 것이고, 브라우저 창에서 localhost:3000 연결이 가능하다.

CreateServer 메소드

  • http.createServer() 메소드는 server 객체를 생성한다.

HTTP server 객체

  • 컴퓨터의 포트를 수신하고 요청이 만들어질 때마다 requestListener라는 함수를 실행할 수 있다.
  • server.listen() 서버를 실행한다. server.close() 서버를 종료한다.

res.writeHead

  • 상태 코드와 응답 헤더를 클라이언트에 보낸다.
    • 응답 헤더를 객체로 전달하고 싶으면, 'Content-Type' : 'application/json'

    • 응답 헤더를 텍스트로 전달하고 싶으면,
      'Content-Type' : 'text/plain'

      res.end

      • 문자열을 받는다.
      • 객체로 전달하고 싶으면 res.end(JSON.stringify({ a: "a" })); 이렇게 문자열로 바꿔줘야한다.

req.url

  • url을 지정할 수 있다.
profile
개발 경험치 쌓는 곳

0개의 댓글