简体   繁体   English

Express.json 未解析 POST 正文 - 未定义

[英]Express.json not parsing POST body - undefined

JSON POST data being received from an IoT API that I want to consume. JSON 从我要使用的 IoT API 接收到的 POST 数据。 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.我想访问 JSON 数据,并且正在使用 express。 As per this SO answer I have tried this approach with express.json():根据这个 SO answer我已经用 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 {} .但是我在控制台上得到的只是undefined {}

UPDATE更新

Even with the correct imports the express/body-parser method does not work.即使导入正确,express/body-parser 方法也不起作用。

This method below works in so far as it proves a POST request is being received.只要证明正在接收 POST 请求,下面的方法就可以工作 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?如何使用 express 获取数据?

You installed body-parser but haven't imported body-parser in order to work.您安装了body-parser但没有导入body-parser才能工作。

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在线试用 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!!试试这个!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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