본문 바로가기

Back-end & Server/Node.js

[Node.js] 클라이언트

728x90
반응형

클라이언트 서버

일반적인 웹의 통신 구조는 다음과 같은 형태이다.

 

클라이언트(Frontend)서버(Backend)가 요청과 응답을 주고 받으면서 서로 통신을 한다.

  • 이때 1:1, 1:N , N:N 형태로 클라이언트와 서버를 구성할 수 있다.

 

서버

Node.js로 웹 서버를 작성해보자.

ex. 웹 서버는 클라이언트가 접속 시 html 파일을 응답으로 전달한다.

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
    if (req.url === "/") {
        // 클라이언트가 루트 페이지에 접속할 때 index.html 파일을 읽어서 응답으로 전송
        fs.readFile("./src/pages/index.html", (err, data) => {
            if (err) {
                res.writeHead(500, { "Content-Type": "text/plain" });
                res.end("Internal Server Error");
            } else {
                res.writeHead(200, { "Content-Type": "text/html" });
                res.end(data);
            }
        });
    } else {
        // 요청한 페이지가 존재하지 않을 경우 404 Not Found 응답
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("Not Found");
    }
});

const port = 3000;
const hostname = "127.0.0.1";
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Hello</title>
    </head>
    <body>
        <h1>Connection Successful</h1>
    </body>
</html>

 

 

클라이언트

서버에 요청을 해서 html의 내용을 가져온다.

const http = require("http");

const options = {
    hostname: "127.0.0.1",
    port: 3000,
    path: "/",
    method: "GET",
};
// 서버에 요청을 전송
const req = http.request(options, (res) => {
    let data = "";

    res.on("data", (chunk) => {
        data += chunk;
    });

    res.on("end", () => {
        console.log(data);
    });
});

req.on("error", (error) => {
    console.error("Error:", error);
});

req.end();

728x90
반응형

'Back-end & Server > Node.js' 카테고리의 다른 글

[Node.js] 자주 쓰는 의존성 패키지  (0) 2023.07.31
[Node.js] Express.js  (0) 2023.07.31
[Node.js] Event Loop  (0) 2023.07.29
[Node.js] Callback Function  (0) 2023.07.29
[Node.js] index.js 파해쳐보기  (0) 2023.07.29