我正在尝试编写一个简单的快速服务器,它接收传入的JSON(POST),解析JSON并分配给请求主体。抓住的是我不能使用bodyparser。下面是我的服务器,其中一个简单的中间件函数被传递给app.use
问题:每当我向我的服务器发送虚假POST请求时,superagent(npm包允许你通过终端发送JSON)我的服务器超时。我使用req.on('data')以类似的方式编写了一个HTTP服务器...所以我很难过。有什么建议吗?
const express = require('express');
const app = express();
function jsonParser(req, res, next) {
res.writeHead(200, {'Content-Type:':'application/json'});
req.on('data', (data, err) => {
if (err) res.status(404).send({error: "invalid json"});
req.body = JSON.parse(data);
});
next();
};
app.use(jsonParser);
app.post('/', (req, res) => {
console.log('post request logging message...');
});
app.listen(3000, () => console.log('Server running on port 3000'));
答案 0 :(得分:23)
我认为问题就是将rawBody放入快递中。
就像这样:
import subprocess
to ='xxxx@fmr.com'
subject= 'hostname'
cmd= "cat /var/log | mailx -s 'swap is full on'+subject" +to
subprocess.Popen(cmd,shell=True)
您需要在将字符串解析为json时捕获错误,并且需要判断app.use(function(req, res, next){
var data = "";
req.on('data', function(chunk){ data += chunk})
req.on('end', function(){
req.rawBody = data;
req.jsonBody = JSON.parse(data);
next();
})
})
的{{1}}。
答案 1 :(得分:0)
another way that worked with me by collecting all chunks into an array and parsing the concatenated chunks.
app.use("/", (req, res, next)=>{
const body = [];
req.on("data", (chunk) => {
console.log(chunk);
body.push(chunk);
});
req.on("end", () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
console.log(parsedBody);
console.log(message);
});
console.log(body);
});
答案 2 :(得分:0)
从 Express v4.16.0 开始:
function createArray(selector, count) {
var current = 0;
var arr = []
while (++current < count) {
arr.push(document.querySelector(selector.replace(/\{#\}/g, current)));
}
return arr;
}