반응형
get과 post 요청에서 form으로 제출한 데이터들을 사용하는법을 알아보자
우선 ejs파일로 form태그 get과 post 요청에 대해 각각 하나씩 만든다.
home.ejs
<%- include('common/head') %>
<%- include('common/nav') %>
<h1>home page</h1>
<h2>get</h2>
<form action="/" method="get">
<input type="text" name="userName">
<input type="text" name="userAge">
<button>제출</button>
</form>
<h2>post</h2>
<form action="/" method="post">
<input type="text" name="userName">
<input type="text" name="userAge">
<button>제출</button>
</form>
<%- include('common/footer') %>
라우터에 get post 요청을 만든다
const express = require('express');
const app = express();
const port = 8080;
const path = require('path'); // 경로
app.use(express.static(path.join(__dirname, 'public'))); // 정적 assets 경로 설정
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views')) // views path 설정
app.get('/', (req, res) => { // get 요청
console.log(req.query)
res.render('home.ejs');
})
app.post('/', (req, res) => { // post 요청
console.log(req.body);
res.render('home.ejs');
})
// 로컬호스트 포트번호 설정
app.listen(port, ()=>{
console.log(`포트 번호 : 8080`);
});
get 요청일 때는 req.query 매서드를
post 요청일 때는 req.body 매서드를 이용해서 제출한 데이터들을 객체로 저장한다.

get 요청같은 경우엔 미들웨어 없이 객체로 잘 저장이 된다.
하지만
post 요청에 경우에는 미들웨어로 구문 분석을 해줘야한다.
그렇지 않으면 req.body에 undefined가 저장된다.

필요한 미들웨어는
urlencoded 이다
express 내장 모듈이기 때문에 따로 설치할 필요는 없다.
자세한건 ejs 문서에 잘 나와 있다.
app.use(express.urlencoded({ extended: true}))
를 추가 해주면 된다.
추가하고

post에 데이터를 넣어서 제출해보면

객체로 잘 불러와진다.
객체를 활용해서 데이터를 출력할 수 도 있다.
app.post('/', (req, res) => {
const {userName, userAge} = req.body;
res.send(`이름 : ${userName} 나이 : ${userAge}`);
})
출력결과

form이 아닌 json구문을 분석해야한다면
app.use(express.json())
을 추가하면 된다
반응형
'nodejs' 카테고리의 다른 글
[node.js] mongoose를 미들웨어로 정의하기 (0) | 2023.05.30 |
---|---|
[node.js / express] REST API, RESTful API, npm(UUID, method_override) CRUD 구현 (0) | 2023.05.19 |
[node.js / express] 정적 assets 과 bootstrap 사용, ejs 파일 분할 (0) | 2023.05.17 |
[node.js / express / ejs] 조건문과 루프(반복문) (2) | 2023.05.15 |
[node.js / express] req.params, 경로 변수로 지정하기 (0) | 2023.05.11 |