0
const express = require('express')
const cors = require('cors')
const app = express()
const PORT = process.env.PORT || 3000;

app.use(cors())

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.all('/hello/', function (req, res, next) {
  res.json({
    'message': 'test',
    'x-result': req.headers['x-test'],
    'x-body': req.body
  })
})

app.listen(PORT, function () {
  console.log('CORS-enabled web server listening on port 3000')
})

Request:

curl 'http://127.0.0.1:3000/hello/' -d 'it is body' -H 'x-test: test'

And I want get this:

{ "message":"test", "x-result":"test", "x-body":"it is body" }

But instead I got this:

{"message":"test","x-result":"test","x-body":{"it is body":""}}

Why and how do the right?

aaltw
  • 17
  • 5
  • 1
    Does this answer your question? [How to force parse request body as plain text instead of json in Express?](https://stackoverflow.com/questions/12345166/how-to-force-parse-request-body-as-plain-text-instead-of-json-in-express) – tbking Sep 17 '21 at 10:58
  • @tbking bodyparser is deprecated; app.use(express.text()) app.use(express.json()) - doesnt work, only app.use(express.urlencoded({ extended: true })) got this body; plain text show this after install - Cannot find module 'plainTextParser' – aaltw Sep 17 '21 at 11:08

1 Answers1

0

You should send the correct content type which in your case is text/plain.

curl 'http://127.0.0.1:3000/hello/' -H 'content-type: text/plain;' -d 'it is body' -H 'x-test: test'

Along with the correct content type, you would want to use express.text() in the application.

app.use(express.text())
tbking
  • 8,796
  • 2
  • 20
  • 33
  • Can I set default request content-type to 'text/plain' to omit "-H 'content-type: text/plain;'"? – aaltw Sep 17 '21 at 14:01
  • If you use, `express.text()` only, and not the other types, the Express will parse the request as `text/plain` without the `content-type` header – tbking Sep 17 '21 at 14:45
  • @aaltw if this answered your question, can you mark it the best answer? – tbking Sep 20 '21 at 11:06