admin管理员组

文章数量:1400093

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'))

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'))
Share Improve this question edited Jun 5, 2021 at 12:53 Apoorva Chikara 8,8033 gold badges23 silver badges38 bronze badges asked Jun 5, 2021 at 11:27 edcjianedcjian 1271 silver badge9 bronze badges 4
  • Can youexplain your problem in little bit more detail? – Jatin Mehrotra Commented Jun 5, 2021 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 Commented Jun 5, 2021 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.expressjs./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 Commented Jun 5, 2021 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 Commented Jun 5, 2021 at 13:17
Add a ment  | 

5 Answers 5

Reset to default 3

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()
})

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 es with two body parser method, try using them like this

app.use(express.urlencoded());
app.use(express.json());

req = Request , res = Response

you need to log req.body

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

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

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

本文标签: javascriptWhy res body is undefined in expressStack Overflow