1

Unfortunately I get an empty body: {} in the request object, when I POST something to my api via Insomnia (configuration Form Form URL Encoded Header Content-Type: application/x-www-form-urlencoded):

Here is my express code:

const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/', function(req, res) {

    test = req.body.test;
    console.log(req);
    console.log(test);
    res.send("Hallo");
});

const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

What am I doing wrong? And also what would I have to change in my code if I'd configure Insomnia to Form as JSON, Header Content-Type: application/json ?

sunwarr10r
  • 4,420
  • 8
  • 54
  • 109

2 Answers2

1

For accessing request body use body-parser middleware and for sending the response in JSON format use res.json()

https://www.npmjs.com/package/body-parser

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.post('/api/', function(req, res) {
    test = req.body.test;
    console.log(req);
    console.log(test);
    res.json({"message":"Hallo"}); //update here
});

const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
1

available in Express v4.16.0 onwards:

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