본문 바로가기

Node.js

mininode-server with Express

1. 먼저 Express 모듈을 install한다.

$ npm install express --save

 

2. cors 미들웨어 install

$ npm install cors

 

미들웨어 : 공통적으로 사용되는 코드를 미들웨어로 처리.

미들웨어는 함수

 

app.use() : 첫번째 파라미터 request객체, 두번째는 response객체, 세번째는 next 변수.

next라는 변수에는 그 다음에 호출되어야 할 미들웨어가 담겨있다.

 

const express = require('express'); //설치한 express 모듈 불러오기
const app = express(); //서버를 만든다.
//express는 함수. return된 값은 app이라는 변수에 담긴다. app변수에는 application이라는 객체가 담긴다.
const port = 5000;
const cors = require('cors');
//cors 미들웨어 불러온다.


app.use(express.json({ strict: false })); //JSON형태로 들어오는 것 파싱한것.
//JSON Request Body 파싱하기
//express로 웹서버를 만들 때, JSON형태의 Request body를 받았을 때, 요청값을 제대로 받아오지 못하는 문제 발생.
//express.json() 모듈을 사용하면 JSON형태의 Request body를 잘 받을 수 있다.
//{strict: false} primitive data type도 parsing..?

app.use(cors());//모든 요청에 대해 CORS 허용

const myLogger = function (req, res, next) {
  console.log(`http request method is ${req.method}, url is ${req.url}`);
  next();
};
//미들웨어는 함수. 첫번째 파라미터 : request 객체, 두번째 파라미터 : response객체, 세번쨰 : next변수
app.use(myLogger); //모든 요청에 대해 미들웨어함수 실행된다.

app.get('/', function (req, res) {
  res.send('Hello World!');
})
//http://localhost:5000 치면 'Hello World!' 이렇게 화면에 뜬다.

app.post('/upper', function (req, res, next) {
  console.log(req.body);//request body부분. JSON --> parsing됨.
  res.json(req.body.toUpperCase()); //json으로 바꿔서 보내줘야한다. stringify로 하거나 res.json으로 해야.
  //next(); 다음 미들웨어 없으니 next()호출 안해도 된다.
})

app.post('/lower', function (req, res, next) {
  console.log(typeof req.body) //어쨌든 이것도 string형태인데 왜 send로 하면 안되는거지? string과 JSON.string은 다른가? ㅇㅇ
  let a = JSON.stringify(req.body);
  res.send(a);
  //next(); 다음 미들웨어 없으니 next()호출 안해도 된다.
})

app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});