내일배움캠프

230612 Nodejs http모듈로 서버 만들어보기

Neda 2023. 6. 12. 20:39

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