gpt4 book ai didi

html - Express 中的 400/500 错误处理程序 - 发送 JSON 与 HTML

转载 作者:可可西里 更新时间:2023-11-01 13:23:48 25 4
gpt4 key购买 nike

我们在 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(/\//));
});

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。我假设查看 Content-Type header 是执行此操作的最佳方法。我应该检查其他方法吗?

Content-Type header 有时不是称为“content-type”(小写)吗?

最佳答案

我更喜欢使用以下内容(这是针对 404 错误,但这并不重要):

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');
}
}

基本上,您可以使用 req 对象的 accepts 方法来确定您应该发送什么作为响应。

关于html - Express 中的 400/500 错误处理程序 - 发送 JSON 与 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42563409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com