node.jsexpresshttppostunirest

Unirest post request body


I want to be able to send data from one server to another, started on the same device (to start with). I have this:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const urlEncodedParser = bodyParser.urlencoded({extended: false});
app.post('/test', urlEncodedParser, (request, response) =>
{
    console.log(request.body);
});
app.listen(9999);
console.log('Server started on port 9999');

const unirest = require('unirest');
unirest.post('http://127.0.0.1:9999/test').headers({'Accept': 'application/json', 'Content-Type': 'application/json'}).send({"test1": 123321, "test2": "321123"})
.then((response) => 
{
    console.log(response.body);
});

It looks logical, but console.log(request.body); gives empty object {} yet in the post requests I do send some data using .send. How to get access to that data in the request?


Solution

  • You are sending data with Content-Type: 'application/json', so on the server you need to connect middleware not for urlencoded, but for json. In addition, you do not need to separately connect the body-parser since it is included in express and you can connect the necessary middleware like this:

    Server:

    const express = require('express');
    
    const app = express();
    
    app.post('/test', express.json(), (request, response) => {
        console.log(request.body);
        response.end('OK');
    });
    
    app.listen(9999, () => console.log('Server started on port 9999'));
    

    Client:

    const unirest = require('unirest');
    
    unirest
        .post('http://127.0.0.1:9999/test')
        .headers({ Accept: 'application/json', 'Content-Type': 'application/json' })
        .send({ test1: 123321, test2: '321123' })
        .then((response) => {
            console.log(response.body);
        });