Express中的400/500错误处理程序-发送JSON与HTML
我们在Express中有此错误处理程序:Express中的400/500错误处理程序-发送JSON与HTML,html,json,express,Html,Json,Express,我们在Express中有此错误处理程序: app.use(function (err, req, res, next) { res.status(err.status || 500); const stck = String(err.stack || err).split('\n').filter(function (s) { return !String(s).match(/\/node_modules\// && String(s).match(/\//)
app.use(function (err, req, res, next) {
res.status(err.status || 500);
const stck = String(err.stack || err).split('\n').filter(function (s) {
return !String(s).match(/\/node_modules\// && String(s).match(/\//));
});
const joined = stck.join('\n');
console.error(joined);
const isProd = process.env.NODE_ENV === 'production';
const message = res.locals.message = (err.message || err);
const shortStackTrace = res.locals.shortStackTrace = isProd ? '' : joined;
const fullStackTrace = res.locals.fullStackTrace = isProd ? '': (err.stack || err);
if (req.headers['Content-Type'] === 'application/json') {
res.json({
message: message,
shortStackTrace: shortStackTrace,
fullStackTrace: fullStackTrace
});
}
else {
//locals for template have already been set
res.render('error');
}
});
我的问题是-我们希望根据请求的类型发回JSON或HTML。我认为查看内容类型标题是最好的方法。有没有其他办法让我检查一下
内容类型标题有时不是被称为“内容类型”(小写)吗?我更喜欢使用以下内容(这是针对404错误的,但这并不重要):
基本上,您可以使用
req
对象的accepts
方法来确定应该发送什么作为响应。谢谢,我将研究req.accepts方法是如何工作的
if (req.accepts('html')) {
// Respond with html page.
fs.readFile('404.html', 'utf-8', function(err, page) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.write(page);
res.end();
});
} else {
if (req.accepts('json')) {
// Respond with json.
res.status(404).send({ error: 'Not found' });
} else {
// Default to plain-text. send()
res.status(404).type('txt').send('Not found');
}
}