Web App Project

HTTP 메서드와 데이터를 전송하는 방식[req.query, req.body 차이]

하얀성 2024. 1. 9. 13:58
const express = require('express')
const ejs = require('ejs')
const cors = require('cors')
const mysql = require('mysql')
const bodyParser = require('body-parser')

require('dotenv').config()

const app = express();
app.use(cors())

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

app.use(bodyParser.urlencoded({ extended: false}))
app.use(express.static(__dirname+'/public'))

const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "1234",
  database: "class"
})

app.get("/", (req, res) => {
  res.render("index")
  // db.query(sql, (err, data) => {
  //   if(err) return res.json("Error")
  //   return res.json(data)
  // })
})

app.get("/profile", (req, res) => {
  res.render("profile")
})

app.get("/map", (req, res) => {
  res.render("map")
})

app.get("/contact", (req, res) => {
  res.render("contact")
})
app.post("/contactProc", (req, res) => {
  const name = req.body.name;
  const phone = req.body.phone;
  const email = req.body.email;
  const memo = req.body.memo;

  let sql = `insert into contact(name,phone,email,memo,regdate)
  values('${name}','${phone}','${email}','${memo}',now())`
 
  connection.query(sql, function(err, result){
    if(err) throw err;
    console.log('자료 1개 삽입완료.')
    res.send("<script>alert('문의사항 등록 완료'); location.href='/';</script>")
  })

})

app.get('/contactDelete', (req, res) => {
  let idx = req.query.idx // 왜 여기선 body가 아니라 query로 쓰였나?
  let sql = `delete from contact where idx='${idx}'`
  connection.query(sql, function(err, result){
    if(err) throw err;
    res.send("<script>alert('삭제 완료'); location.href='/contactList';</script>")
  })
})

app.get("/contactList", (req, res) => {
  let sql = `select * from contact`;
  connection.query(sql, function (err, results, fields){
    if(err) throw err;
    res.render('contactList',{lists:results})
  })
})

app.listen(8081, () => {
  console.log("Listening... http://localhost:8081")
})

 

 

왜 주석으로 표시된 곳에는  body가 아니라 query로 쓰였나?

 

get 에서는 req를 받을 때 req.query로 url로부터 받고,

post 에서는 req를 받을 때 req.body로 폼 같은 본문 전체에서부터 받는다.

 


app.get("/contactDelete", (req, res) => { ... })에서 req.query를 사용하는 이유는 HTTP GET 요청이 데이터를 URL의 쿼리 스트링을 통해 전송하기 때문입니다. 즉, 클라이언트가 서버로 정보를 보낼 때, URL의 일부로 데이터를 전송합니다. 예를 들어, /contactDelete?idx=123 URL은 idx의 값을 123으로 서버에 전송합니다. req.query는 이 쿼리 스트링에 접근하는 데 사용됩니다.

 

반면에, app.post("/contactProc", (req, res) => { ... })에서 req.body를 사용하는 이유는 HTTP POST 요청이 데이터를 요청 본문(request body)에 포함하여 전송하기 때문입니다. POST 요청은 헤더와 별개로 요청 본문에 데이터를 담아서 보내며, 주로 폼 데이터를 서버로 전송할 때 사용됩니다. req.body는 bodyParser 미들웨어를 통해 이 본문에 접근할 수 있게 해줍니다.

 

요약하자면:

  • req.query: URL의 쿼리 스트링으로부터 데이터를 가져오는 데 사용됩니다. 주로 GET 요청에서 사용됩니다.
  • req.body: POST 요청의 본문으로부터 데이터를 가져오는 데 사용됩니다. 이는 body-parser 같은 미들웨어가 필요합니다.