본문 바로가기
Node.js/Node.js | Express.js

Body Parser 사용하기

by CodeMia 2021. 10. 3.

Body Parser

계산기 서버 만들 때

숫자를 서버에 입력받고 나면

서버가 계산 한 후

그 결과를 브라우저에 보낼 수는 없을까?

 

이 때 npm package 에서 Body Parser가 필요하다.

https://www.npmjs.com/package/body-parser

 

 

 다운받기 

npm install body-parser을 써서 다운을 받자.

 

다운로드 후 package.json에서 body-parser가 들어가있는 것을 볼 수 있다. 

 

 

 

bodyParser 모드 

bodyParser는 몇 가지 모드가 있다. 

 

bodyParser.text() :

parse all the requests into text

parse 팔-ㅆ : 분석하다

 

 

bodyParser.json() :

special format that we saw before which kind of looks a bit like Javascript objects

 

 

bodyParser.urlencoded():

HTML폼에서 온 데이터를 분석한다. 

whenever you're trying to grab the information that gets posted to your server from an HTML form 

 

 

bodyParser.urlencoded(extended: true) :

nested objects를 post 할 수 있다. 

it's not sth that we're going to be using, but it's sth that bodyParser is requiring you to explicitly declare. 

app.use(bodyParser.urlencoded({extended:true}));

 

 

 

bodyParser 사용하는 이유

it allows you to go into any of your routes,

and you can tap into(활용하다) sth called request.body 

and this is the parsed version of the HTTP request. 

 

1 bodyParser 불러오기 

2 html 파일 분석

3 계산기 숫자 입력시 첫 번째 숫자 콘솔에 나오게하기 

4 num1은 html name attribute에서 왔음

num1을 n1으로 바꾸면 js에서도 바꿔줘야한다. 

 

 

 

결과보기  

첫 숫자 7

 

 

두 숫자 더한 값 나오게하기 

 

 

 

결과보기 (실패한 결과)

 

4와 5를 입력하였다

 

둘의 더한 값이 아니라 그냥 45로 출력되었다. 

 

이유는 입력값이 텍스트로 인식되었기 때문이다.

숫자로 바꿔줘야한다. 

 

이제 더한 값이 나왔다. 

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

 

app.get("/", function(req, res) {

res.sendFile(__dirname + "/index.html");

});

 

app.post("/", function(req, res) {

var num1 = Number(req.body.num1);

var num2 = Number(req.body.num2);

var result = num1 + num2;

 

res.send("The result of the calculation is " + result);

})

 

app.listen(3000, function() {

console.log("Server started on port 3000");

});

 

 

 

'Node.js > Node.js | Express.js' 카테고리의 다른 글

BMI 계산기 서버 만들기  (0) 2021.10.03
백엔드에서 일어나는 일  (0) 2021.10.03
자바스크립트 파일 경로 알아보기  (0) 2021.10.03
POST 요청  (0) 2021.09.28
Get 요청 | sendFile() | __dirname  (0) 2021.09.28

댓글