1

Why res. body is undefined in express how can I get response body, Is there something wrong?

import {createProxyMiddleware} from 'http-proxy-middleware'
import bodyParser from 'body-parser'
import mung from "express-mung";

const app = express();


app.use(((req, res, next) => {
    console.log(res.body)

    next()
}))

app.get('/as', function (req, res, next) {

    res.send("123")
})
app.listen(3001, () => console.log('start in http://localhost:3001'))
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
edcjian
  • 77
  • 1
  • 7
  • Can youexplain your problem in little bit more detail? – Jatin Mehrotra Jun 05 '21 at 11:33
  • I want to view the content of res.send in middleware and modify it, but the result res.body is always undefined – edcjian Jun 05 '21 at 11:52
  • `app.use(function (req, res, next) { console.log('Time:', Date.now()) next() })` this code is executed every time app receives a request. when you get a request through get you can see console.log(req) but in express it is from server side to sen data using res object, so its natural to get res.body undefined.http://expressjs.com/en/api.html#res. ALso if it was a post request with some data then also you would be using req.body and not res.body. req object is what you get, res is what you send from server. – Jatin Mehrotra Jun 05 '21 at 12:03
  • @edcjian Is the intention here to mutate the body before sending it back to the client? i.e. you want `res.body` to give you `"123"` after `res.send()` is called? – samthecodingman Jun 05 '21 at 13:17

5 Answers5

1

This answer is what I expected and solved my problem

express.js - how to intercept response.send() / response.json()

app.use((req, res, next) => {
    let oldSend = res.send
    res.send = function(data) {
        console.log(data) // do something with the data
        res.send = oldSend // set function back to avoid the 'double-send'
        return res.send(data) // just call as normal with data
    }
    next()
})
edcjian
  • 77
  • 1
  • 7
1

It looks like you haven't parsed the body data yet.

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

Express comes with two body parser method, try using them like this

app.use(express.urlencoded());
app.use(express.json());
cachique
  • 1,150
  • 1
  • 12
  • 16
7usam
  • 23
  • 1
  • 6
0

req = Request , res = Response

you need to log req.body

app.use(((req, res, next) => {
    console.log(req.body)
    next()
}))
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0

just check my logic if it helps you,

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

In-order to print something in console for req.body , u need to pass a "body" from where u call this . eg refer screenshot enter image description here

0

Express not like koa, response has no 'body' attribute, but you can create a custom middleware to resolve this, there is an example:

const logResponseBodyMiddleware = (req, res, next) => {
  const selfWrite = res.write
  const selfEnd = res.end
  const chunks = []

  res.write = (...args) => {
    const chunk = args[0]
    chunks.push(chunk)
    return selfWrite.apply(res, args)
  }
  res.end = (...args) => {
    const chunk = args[0]
    if (chunk) chunks.push(chunk)
    res.body = Buffer.concat(chunks).toString('utf8')
    selfEnd.apply(res, args)
  }

  next()
}

app.use(logResponseBodyMiddleware)
  • Node.js: 12.21.0
  • Express: 4.17.1

reference:

http_response_write
http_response_end