코딩쌀롱

[Node.js] express 예시로 코드 설명 본문

개발공부

[Node.js] express 예시로 코드 설명

이브✱ 2021. 3. 2. 00:53

 

const express = require('express')
const app = express()
app.listen(3000, function() {
   console.log('start! express server on port 3000);
}

app.listen(3000, 함수) 

3000포트를 기반으로 함수 실행, 대기 중인 상태로 머물러있음

localhost:3000은 127.0.0.1:3000과 같다.

 

// (1)
app.get('/', function(req, res) {
	res.send("<h1>codingSalon</h1>")
})

// (2)
app.get('/', function(req, res) {
    res.sendFile(__dirname + "public/main.html")
})

app.get('/', 함수) 

get요청 url 경로를 먼저 적어주고, request, response 인자를 줘서 콜백함수를 줌

(1) res.send() : 응답 보내주기

(2) res.sendFile() : 파일을 보내줄 수도 있다. 인자로 절대경로를 다 적어줘야하지만 __dirname은 현재 app.js파일의 경로가 저장되어 있다. 그래서 __dirname + 그 이후의 경로를 적어주면 된다.



app.use(express.static('public'))

 app.use(express.static('폴더명')) 

변경되지 않는 정적인 파일(javascript, css, images 등) static파일을 지정해두고 "이 요청이 오면 그냥 줘~"라고 서버에게 하는 것. app.use는 미들웨어 등록하는 라우터이고 stati은 express 기본 미들웨어이기 때문에 설치 없이 사용 가능. express가 디렉토리 'public'을 static폴더로 기억하고 public 아래에 있는 파일들은 바로 static으로 접근 가능.

 

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

   email : <input type="text" name="email"> <br/>
   <input type="submit">
   
</form>

<form> action, method  /  <input> name

action은 서버에 어디로 보낼 것인지, method는 어떤 메소드로 보낼 것인지.

name은 서버에서 받을 때 객체의 키값이 됨.

 

app.post('/email_post', function(req, res) {
   res.send('post response')
})

app.post('경로', 함수)

해당 경로로 post 요청이 왔을 때 함수 실행. (경로는 form태그의 action의 경로)

get이 데이터를 받아올 때는 req.param으로 받아올 수 있지만 post는 body-parser라는 모듈이 필요(npm 설치)

 

const bodyParser = require('body-parser')
// 익스프레스 4.16.0 버전부터 body-parser 미들웨어의 일부기능이 내장되었으므로 설치할 필요 없다.

app.use(bodyParser.json())                       // → req.body
app.use(bodyParser.urlencoded({extended: true})) // → req.body

app.post('email_post', function(req, res) {
   console.log(req.body)
})

 

body-parser 미들웨어

요청의 본문에 있는 데이터를 해석해서 req.body 객체로 만들어주는 미들웨어. 보통 form 데이터나 ajax 요청의 데이터를 처리. 단, 멀티파트(이미지, 동영상, 파일) 데이터는 처리하지 못함(이건 multer 미들웨어로 가능)

 app.use(bodyParser.json())

json 형식의 데이터 전달 방식

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

주소 형식으로 데이터를 보내는 방식. form 전송은 URL-encoded 방식을 주로 사용.

 extended 옵션은 false면 노드의 querystring 모듈을 사용해 쿼리스트링을 해석, true면 qs 모듈을 사용해 쿼리스트링을 해석. (qs는 내장모듈이 아닌 npm 패키지이고, querystring 기능을 더 확장한 모듈이다.)

req.body

body-parser 미들웨어가 만드는 요청의 본문을 해석한 객체

클라이언트에서 보낸 것들이 객체로 들어있다. input태그의 name 속성값이 이 객체의 키가 된다.

 

app.set('view engine', 'ejs')

app.post('/email_post', function(req, res) {
   res.render('email.ejs', {'email': req.body.email})
})

app.set('view engine', 'ejs')

뷰엔진은 ejs 쓰겠다고 express에게 알려줌. views라고 지정된 디렉터리가 있고, 그 안에 ejs파일을 작성한다.

res.render('email.ejs', {~})

email.ejs에 객체의 키를 값으로 치환해서 클라이언트에 응답해줌.

위의 코드로 예시를 들면, email.ejs에서 email은 req.body.email이 된다.

 

 

 

 

 

Comments