const http = require('http')
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
// html 이라는것과 한글이 들어갔을수 있으니, 추가내용
res.write('<h1>hellow node!</h1>')
res.write('<p>hellow server</p>')
res.end('<p>hellow doha</p>')
})
.listen(8080, () => {
// port
console.log('8080번 포트에서 서버 대기중')
})
// http도 비동기이기 때문에 애러처리를 해주어야 한다.
html이 길어진다면 따로 파일을 만들어주는것이 보기 좋다.
const http = require("http");
const fs = require("fs").promises;
http
.createServer(async (req, res) => {
try {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
const data = await fs.readFile("./server2.html");
res.end(data);
} catch (error) {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
console.error(error);
res.end(err.message);
}
})
.listen(8080, () => {
console.log("8080번 포트에서 서버 대기중");
});
reqest의 method의 종류에 따라서 분류가 되고
그 내부에서 url이 무엇이냐에 따라 실행될 코드가 달라진다.
이렇게 하면 코드를 읽기가 힘들어지므로 express 를 사용하곤 한다.
const http = require('http');
const fs = require('fs').promises;
const path = require('path');
http.createServer(async (req, res) => {
try {
if (req.method === 'GET') {
if (req.url === '/') {
// ...
} else if (req.url === '/about') {
// ...
} else if (req.url === '/users') {
// ...
}
// /도 /about도 /users도 아니면
try {
const data = await fs.readFile(path.join(__dirname, req.url));
return res.end(data);
} catch (err) {
// 주소에 해당하는 라우트를 못 찾았다는 404 Not Found error 발생
}
} else if (req.method === 'POST') {
if (req.url === '/user') {
// ...
}
}
// ...
res.writeHead(404);
return res.end('Not Found');
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' })
res.end(err.message);
}
.listen(8082, () => {
console.log('8082번 포트에서 서버 대기 중입니다');
});