요청과 응답

const http = require('http');

http.createServer((req,res) =>
{
    res.writeHead(200,{'Content-Type': 'text/html; charset=utf8'});
    res.write('<h1>Hello Node</h1>');
    res.end('<p>Hello Server!</p>');
})
.listen(8080,() =>
{
    console.log('8080 대기중');
});

서버를 실행 후 localhost:8080 로 접속하면 결과를 볼 수 있다.

* localhost : 현재 컴퓨터의내부 주소로 외부에서 접근이 불가능

* 포트 : 서버 내에서 프로세스를 구분하는 번호 (8080)

 

Ctrl + C 를 입력하여 서버를 종료할 수 있다.

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Node.js 웹 서버~</title>
    </head>
    <body>
        <h1>Node.js 웹 서버 :)</h1>
        <p>하나도 모르겠어요~<br>
            이거 저장하니까 바로 반영되네<br>
            'br'이 줄바꿈이네<br>
            그래도 모르겠다<h3>이건뭐지</h3>
            <input>이건 머지
        </p> 
    </body>
</html>
const http = require('http');
const fs = require('fs').promises;

const server = http.createServer(async (req,res) =>
{
    try
    {
        const data = await fs.readFile('./server2.html');
        res.writeHead(200,{'content-Type': 'text/html; charset=utf-8'});
        res.end(data);
    }
    catch (err)
    {
        console.error(err);
        res.writeHead(500,{'content-Type': 'text/plain; charset=utf-8'});
        res.end(err.message);
    }
});
server.listen(8080);

server.on('listening',() =>
{
    console.log('8080 대기중');
});

server.on('error', (error)=>
{
    console.error('Error 발생');
});

 

728x90

'Program > Server' 카테고리의 다른 글

[Photon] Zombie로 포톤 배우기  (0) 2022.09.13
[Photon] 서버 개요  (0) 2022.09.13
[NodeJS] 노드 내장 모듈  (0) 2022.09.13
[NodeJS] Process  (0) 2022.09.13
[NodeJS] 이론  (0) 2022.09.06

+ Recent posts