我有一个快递应用程序,它处理像这样的后请求正文:
var app = express();
app.use(bodyParser.text({ type: "*/*" }));
app.post(url, function(req, res) {
//Process req.body, handle the errors along the way;
});
现在,如果发生某些错误,我希望能够记录整个请求。我的意思是标题,正文和所有内容。好像您在使用wireshark查看请求一样。
有谁知道最简单的方法是什么?
这是一个HTTP POST请求示例(从此处获取):
POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom
当我遇到错误时,我需要这个。
您可以使用错误处理中间件:
app.use(function(err, req, res, next) {
// define log format, for example:
let data = `URL: ${req.originalUrl} - method: ${req.method} - error: ${err.message}`;
// append to log file
fs.appendFile('server.log', data, function (err) {
if (err) throw err;
// terminate the request/response cycle
res.status(err.status || 500);
res.json({ error: err });
});
});
通过调用next(err)
,跳转到错误处理中间件,例如:
app.get('some/route', function (req, res, next) {
someFunction( req.body, function (err) {
// pass err object to the error middleware
if (err) return next(err);
return res.json({ success: true });
});
});
希望这可以帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句