201128 TIL Express.js

ToastEggsToast·2020년 11월 30일
0

NodeJs

목록 보기
4/4

Express.js

What is Express.js?

Node Js의 프레임워크 툴로, Node Js를 좀 더 쉽고, 재미있고, 짜릿하게(? 사용할 수 있도록 해준다.

Using Middleware

Request => MiddleWare ( next( ) ) => Middleware ( res.send( ) ) => Response

const http = require("http");

const express = require("express");

const app = express();
// initialize new function Object

// MiddleWare: After initialize the express as function, and Before the server has created.

app.use((req, res, next) => {
  // next: function. executed allow travel to next page
  console.log("In the middleware!");
  next();
  // next를 부르지 않으면, 이 뒤로는 진행되지 않음!!!!
});
// Make Using new MiddleWare

app.use((req, res, next) => {
  console.log("In the another middleware!");
  res.send("<h1>Hello express js!</h1>");
  // send our response. could send html code,
});

const server = http.createServer(app);

server.listen(3000);

Working with Request & Responses

req로 받아온 것에 대한 응답을 처리해줄 수 있다.
res.send("") 등을 이용해 html dummy를 보내줄 수 있고,
res.redirect("")로 페이지를 옮겨줄수도 있다.

Routing

요청을 보내는 url에 따라 다른 값을 보내줄 수 있는데,
기존에는 app.use((req,res,next)=>{ })를 사용했다면 url을 구분하기 위해서는
app.use("/user",(req,res,next)=>{ })를 사용해 받는 url을 구분할 수 있다.
routes 폴더를 만들어서 새로 관리하는 방법도 있다.
그럴 경우 app.js 파일에서 해당 모듈을 임포트 해온 뒤, 사용해주면 된다.

Returning HTML Pages(Files)

html file을 보내주기 위해서는
1. res.send 대신에 res.sendFile을 사용한다.
2. path module을 임포트해서 보내려는 파일의 경로를 설정해준다.

res.sendFile(path.join("root"))
profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글