230612 Nodejs http모듈로 페이지 만들어보기
nodejs http 서버 열기
http 서버 만들기
const http = require("http");
const port = 3000;
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('server is open');
});
server.listen(port, () => {
console.log(`Server running at port ${port}`);
});
'/' 경로로 들어왔을 때 응답 보내기
const http = require("http");
const port = 3000;
const server = http.createServer((req, res) => {
const url = req.url;
if (url === "/") {
fs.readFile('index.html', "utf8", (err, data) => {
if (err) {
res.end("404 error");
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
}
});
} else {
res.end('server is open');
}
});
server.listen(port, () => {
console.log(`Server running at port ${port}`);
});
json으로 api 응답 보내기
const http = require("http");
const port = 3000;
const db = {
users: {
0: { id: 0, name: "Yeong Seulgi", age: 20 },
1: { id: 1, name: "Seong Hwan", age: 24 },
2: { id: 2, name: "Chu Chun-Hei", age: 34 },
3: { id: 3, name: "Cha He-Ran", age: 12 },
4: { id: 4, name: "Mun Young", age: 38 },
},
};
const server = http.createServer((req, res) => {
const url = req.url;
if (req.method === "GET" && req.url === "/api/users") {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(db.users));
} else {
res.end('server is open');
}
});
server.listen(port, () => {
console.log(`Server running at port ${port}`);
});
없는 경로 접근 시 리디렉션하기
res.writeHead(301, { Location: "/404" });
res.end();
const http = require("http");
const port = 3000;
const server = http.createServer((req, res) => {
const url = req.url;
if (url === "/") {
fs.readFile('index.html', "utf8", (err, data) => {
if (err) {
res.end("404 error");
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
}
});
} else {
res.writeHead(301, {
Location: "/404",
});
res.end();
}
});
server.listen(port, () => {
console.log(`Server running at port ${port}`);
});
HTTP 트랜잭션 해부 | Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
HTTP | Node.js v6.17.1 Documentation
HTTP# To use the HTTP server and client one must require('http'). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. T
nodejs.org
Node.js HTTP Module
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
'내일배움캠프' 카테고리의 다른 글
230614 React 투두리스트 localStorage에 저장하기 (0) | 2023.06.14 |
---|---|
230613 React contentEditable 속성을 가진 요소의 커서 초기화 문제 (0) | 2023.06.13 |
2306011 내일배움캠프 4주차 WIL (0) | 2023.06.11 |
230610 stackblitz에서 nodejs 프로젝트 npm 명령어 자동 실행하기 (0) | 2023.06.10 |
230609 git rebase (1) | 2023.06.09 |