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

BMI 계산기 서버 만들기

by CodeMia 2021. 10. 3.

앞에서 만든 계산기 서버 폴더 안에

BMI 서버를 만들어 보자. 

 

 

1 새 파일을 만든다.

 bmiCalculator.html 

 

 

 

2 html 내용을 입력한다. 

버튼 타입을 button으로 해놔서 숫자 입력해도 아무 일도 일어나지 않았었다. 

버튼 타입을 submit으로 해야 입력 내용이 서버로 간다. 

 

 

 

3 서버를 만든다. 

 

새 자바스크립트 파일을 만드는 것이 아니라

이미 만들어 놓은 calculator.js 파일에

내용을 추가하면 된다. 

 

express, nodemon, body-parser는

이미 실행 중이므로 다시 실행할 필요가 없다.

 

입력값을 Number()로 감싸지 않고, parsefloat()로 감쌌다. 왜 그랬을까..?

 

 

 

 

HTML 

 

<!DOCTYPE html>

<html lang="en">

 

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>BMI Calculator</title>

</head>

 

<body>

<h1>BMI Calculator</h1>

<form action="/bmicalculator" method="post">

<input type="text" name="weight" placeholder="Weight">

<input type="text" name="height" placeholder="Height">

<button type="submit">Calculate BMI</button>

</form>

</body>

 

</html>

 

 

Javascript

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 calculator is " + result);

});

 

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

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

});

 

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

var weight = parseFloat(req.body.weight);

var height = parseFloat(req.body.height);

var bmi = weight / (height * height);

res.send("Your BMI is " + bmi);

});

 

app.listen(3000, function() {

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

});

 

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

Node.js 이전 버젼으로 옮길려면 | NVM  (0) 2022.02.02
백엔드에서 일어나는 일  (0) 2021.10.03
Body Parser 사용하기  (0) 2021.10.03
자바스크립트 파일 경로 알아보기  (0) 2021.10.03
POST 요청  (0) 2021.09.28

댓글