본문 바로가기
Unity/수업 내용

[웹 프로그래밍] - html 파일읽어서 응답 하기

by 이지훈26 2021. 12. 17.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Node.js 웹 서버</h1>
    <p>만들 준비되셨나요?</p>    
</body>
</html>

마우스 우클릭으로 서버 열기

 


const http = require('http');
const fs = require('fs').promises;

http.createServer(async(req, res)=>{

    const buffer = await fs.readFile('./server2.html');
    res.end(buffer);    

}).listen(8080, ()=>{
    console.log('8080포트에서 서버 시작됨...');
});

-> promises

 

 

const http = require('http');
const fs = require('fs').promises;

http.createServer(async (req, res)=>{
    try{
        const buffer = await fs.readFile('./server2.html');
        res.writeHead(200, { 'Content-Type': 'text.html; charset=utf-8' });
        res.end(buffer);
    }catch(err){
        console.error(err);
        res.writeHead(500, { 'Content-Type': 'text.html; charset=utf-8' });
        res.end(err.message);   //오류메시지를 응답 
    }
}).listen(8080, ()=>{
    console.log('8080포트에서 서버 시작됨...');
});