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?