简体   繁体   中英

Express.json not parsing POST body - undefined

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?

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

输出

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM