본문 바로가기

프로그래밍 공부/백엔드

Calculator 만들기: res.sendFile(__dirname

728x90

calculator.js

더보기
const express = require("express");
const app = express();

 

app.get("/", function(req, res) {
    res.sendFile (__dirname + "/index.html");
);
});

 

app.listen(3000, function() {
console.log ("Server started on port 3000");
});

 

index.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>Calculator</title>
</head>
<body>
<form action="/" method="post">
    <input type="text" name="num1" placeholder="First Number">
    <input type="text" name="num2" placeholder="Second Number">
    <button type ="submit" name="submit">Calculator</button>
</form>
</body>
</html>

 

1. res.sendFile

res.send("Hello World")는 입력값(Hello World)을 출력했고

sendFile은 괄호내의 주소의 파일(index.html) 을 출력한다.

 

2. __dirname

로칼 내부에서 주소는 이때까지, index.html을 치면, 현재 폴더 안에서 그 파일을 찾을 수 있었지만

브라우저로 이동되어 서버에 올라가면 그런 방식으로 안된다고 한다.

 

__dirname 은 서버이 올라가서도, 현재 폴더의 주소를 상수값으로 만들어주어 불러올 수 있게 한다.

예를 들어, dirname을 콘솔로그 해보겠다. (?)

app.get("/", function(req, res){
console.log(__dirname);
});

콘솔 화면에 c/ 바탕화면/ 폴더이름 등이 떠야하는데

__dirname은 프로젝트가 있는 폴더의 로컬 주소

사진처럼 떠야하는데, 내 하이퍼 화면은 node calculator.js 하면 그 후로 ctrl c 할때까지 먹통이다 ㅠㅠ 왜?

 

3-1. <form action="/" method="post"> ~ input, button </form>

form에 액션이 있고, 방법(method)는 포스트이다.

이 데이터는 액션이 정한 요소로 보내지는데, 그게 우리 서버인 홈 라우트 주소"/"이고, 

action="/" 은 생략 가능하다. default 값이라서.

 

3-2. app.post()

method가 post이면, js file에서 post를 받아줘야 한다. 그게 바로 app.post("/", function(req, res){ } )

 

4. body-parser

urlencoded() : this is special on that we use when we're trying to parse data that comes from an HTML form. 

so whenever you're trying to grab the information that gets posted to your server from an HTML form, you're  going to be using  urlencoded. In addition to that, setting extended: true, that basically just allows us to post nested objects. And it's not something that we're going to be using, but it's something that bodyParser is requiring you to explicitly declare.

So, this is the code that you need every single time you want to use Body Parser:

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

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