[Web Server] 기초 # Express 2: 요청 객체와 응답객체(req & res)

hosik kim·2021년 11월 17일
0

With CodeStates

목록 보기
17/45
post-thumbnail

💡 req & res


: 익스프레스에서 사용하는 요청(req-Request) 객체와 응답(res-Response) 객체는 http 모듈에서 사용하는
객체들과 같지만, 몇 가지 메소드를 더 추가할 수 있다.

🔸응답 객체 주요 메소드


메소드 이름설명
send([body])클라이언트에 응답 데이터를 보낸다. 전달할 수 있는 데이터엔 HTML 문자열, Buffer 객체, JSON 객체, JSON 배열 등이 있다.
status(code)HTTP 상태 코드를 반환한다. 상태 코드는 end()나 send() 같은 전송 메소드를 추가로 호출해야 전송할 수 있다.
sendStatus(statusCode)HTTP 상태 코드를 반환한다. 상태 코드는 상태 메세지와 함께 전송된다.
redirect([status,]path)웹 페이지 경로를 강제로 이동시킨다.
render(view, [,locals][, callback])뷰 엔진을 사용해 문서를 만든 후 전송한다.

res.send([body])

res.send(Buffer.from('whoop'))
res.send({some: 'json'})
res.send('<p>some html</p>')
res.status(404).send('Sorry, we cannot find that!')
res.status(500).send({error: 'something blew up'})

res.status(code)

res.status(403).end()
res.status(400).send('Bad request')
res.status(404).sendFile('/absolute/path/to/404.png')

res.sendStatus(statusCode)

res.sendStatus(200) // equivalent to res.status(200).send('ok')
res.sendStatus(403) // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404) // equivalent to res.status(404).send('Not Found')
res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')

res.render(view), [, locals][, callback])

//send the rendered view to the client
res.render('index')

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function (err, html){
 res.send(html)
})

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function (err, html){
  // ...
})

🔸요청 객체의 주요 속성


: 익스프레스에서 요청 객체에 추가한 헤더와 파라미터는 다음과 같은 속성(property)에 접근하여 확인할 수 있다.

추가한 정보설명
query클라이언트에서 GET 방식으로 전송한 요청 파라미터를 확인한다.
body클라이언트에서 POST 방식으로 전송한 요청 파라미터를 확인한다. 단, express.json()이나 express.urlencoded()와 같은 미들웨어를 사용해야한다.
get(field), header(field)헤더를 확인한다.

req.query

// GET /search?q=tobi+ferret
console.dir(req.query.q)
// => 'tobi ferret'

// GET / shoes?order=desc&shoe[color]=blue&shoe[type]=converse
console.dir(req.query.order)
// => 'desc'

console.dir(req.query.shoe.color)
// => 'blue'

console.dir(req.query.shoe.type)
// => 'converse'

// GET /shoes?color[]=blue&color[]=black&color[]=red
console.dir(req.query.color)
// => ['blue', 'black', 'red']

req.body

const express = require('express')
const app = express()

app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true})) // for parsing application/x-www-form-urlencoded

app.post('/profile', function (req, res, next) {
  console.log(req.body)
  res.json(req.body)
})

클라이언트에서 요청할 때 GET 방식으로 요청할지, 아니면 POST 방식으로 요청할지 모르는 경우가 있을 수도 있다.
이럴 때는 다음과 같은 방식으로 두 가지 요청 파라미터를 모두 검사할 수 있다.

const paramID = req.body.id || req.query.id;

req.get(field), req.header(name)

req.get('Content-Type')
// => "text/plain"

req.get('content-type')
// => "text/plain"

req.get('Something')
// => undefined

🔍Reference


profile
안되면 될 때까지👌

0개의 댓글