1

JSON POST data being received from an IoT API that I want to consume. Note the multipart form-data. Sometimes an image file can be attached, but I am not interested in processing the image part:

POST {
  host: '192.168.78.243:3000',
  accept: '*/*',
  'content-length': '1178',
  'content-type': 'multipart/form-data; boundary=------------------------f519f81dc2e1d562'
}
--------------------------f519f81dc2e1d562
Content-Disposition: form-data; name="event"; filename="event_3913.json"
Content-Type: application/octet-stream

{"packetCounter":"3913",
"capture_timestamp":"1600677267347",
"datetime":"20200921 204027000",
"stateUTF8":"ABC123",
"stateASCII":"ABC123",
.....

I want to access the JSON data, and are using express. As per this SO answer I have tried this approach with express.json():

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

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

app.post('/test', (req, res) =>{
    if (req.method === 'POST') {
        console.log('POST request recd');
    }
    console.log(req.body);
    res.status(200).send('It works');
});

app.listen(3000, () => console.log('server started'));

However all I get on console is undefined {}.

UPDATE

Even with the correct imports the express/body-parser method does not work.

This method below works in so far as it proves a POST request is being received. But I need to use a express method so that I can access the incoming data:

let buffers = [];
const http =require('http')
http.createServer((request, response) => {
    console.log('Now we have a http message with headers but no data yet.');
    if (request.method === 'POST' && request.url === '/test') {
        console.log('Hit');
    }
    request.on('data', chunk => {
        console.log('A chunk of data has arrived: ', chunk);
        buffers.push(chunk);
    });
    request.on('end', () => {
        console.log('No more data');
        let body = Buffer.concat(buffers);
        console.log(String(body));
    })
}).listen(3000)

How do I get to the data with express?

Al Grant
  • 2,102
  • 1
  • 26
  • 49
  • You could use the body-parser middleware http://expressjs.com/en/resources/middleware/body-parser.html – BraveButter Sep 21 '20 at 09:48
  • I have tried app.use(express.bodyParser()); and installed with npm install --save body-parser but I still get body-parser needs to be installed separately?? – Al Grant Sep 21 '20 at 09:50
  • you also need to require it separately, it's not part of express – stranded Sep 21 '20 at 10:00
  • You have mentioned that data coming from API looks like .... so I want to know are you hitting an api from the server or there is some frontend from which that data is coming to your server? (please elaborate about the purpose of your application) also, from Express version 4.16+ body parser is not requires – Nisha Dave Sep 21 '20 at 10:07
  • @NishaDave the API data is coming from a IOT device. – Al Grant Sep 21 '20 at 10:44

2 Answers2

2

You installed body-parser but haven't imported body-parser in order to work.

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

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

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.sendFile('public/index.html');
}); 

app.post('/test', (req, res) =>{
  console.log(req.body);
  res.status(200).send('It works');
});

app.listen(3000, () => console.log('server started'));

Updated Answer

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

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

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.send(`<form action="/test" method="POST" >
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"><br><br>
  <label for="lname">Last name:</label>
  <input type="text" id="lname" name="lname"><br><br>
  <input type="submit" value="Submit">
</form>`)
}); 

app.post('/test', (req, res) =>{
  console.log(req.body);
  res.status(200).send('It works');
});

app.listen(3000, () => console.log('server started'));

Try it online https://repl.it/join/ldopaeji-pprathameshmore

output

Prathamesh More
  • 1,470
  • 2
  • 18
  • 32
0
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('192.168.78.243:3000/', (req,res) =>{
console.log(req.body.stateUTF8);
console.log(req.body);
res.sendStatus(200);
});
app.listen(3000, ()=> console.log('listening'));

Try this!!