0

i'm developing a node.js api for a simple app for the first time and i'm confused about receiving data on body.

The code:


router.route("/ReceiveJSON").get((request, response) => {

    console.log(request.body);
    response.send("ok");
});

I'm sending this on Postman to test:

{
    "name": "test"
}

So i'm supposed to get this text on console, but i only get "{}" on console.

What am i doing wrong?

I dont know if this is causing the problem but i algo got the message "(node:11396) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated (Use node --trace-deprecation ... to show where the warning was created)" on console (but im not even using headers)

abrev
  • 153
  • 12
  • So you're trying to send data as JSON meanwhile to process them on server-side as url encoded? – Anatoly Jan 27 '21 at 13:56
  • the urlencoded part was a test, doenst work even without it – abrev Jan 27 '21 at 13:58
  • 1
    Does this answer your question? [How do I consume the JSON POST data in an Express application](https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application) – goto1 Jan 27 '21 at 14:00
  • No, i did like the example and still got empty. – abrev Jan 27 '21 at 14:35
  • 1
    @abrev to figure out the problem we'll need the full configuration code for your express app and the cURL of the request you attempt and get empty body instead. You can use [Postman](https://www.postman.com/) to get the cURL after you try your request. – Onheiron Jan 27 '21 at 15:19
  • 1
    @abrev I'm not familiar with Postman but are you setting the `Content-Type` header to `application/json`? `body-parser` expects this by default. – adrian Jan 27 '21 at 17:09
  • The problem was the header! Thanks. – abrev Jan 27 '21 at 19:15

1 Answers1

1

Hi you can try to use express like in this example:

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

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

app.use(express.json())

app.post('/todos', (req, res) => {
  console.log(req.body.todo)
})

I don't test it actually.

Micha
  • 730
  • 3
  • 8