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

时间:2017-03-02 18:42:57

标签: html json express

我们在Express中有这个错误处理程序:

Array
(
    [0] => 10_1
    [1] => 2_2
    [2] => 3_4
    [3] => 1_6
    [4] => 5_7
)

我的问题是 - 我们希望根据请求的类型发回JSON或HTML。我假设查看Content-Type标头是执行此操作的最佳方式。还有其他方法我应该检查吗?

不是Content-Type标题,有时称为' content-type' (小写)?

1 个答案:

答案 0 :(得分:2)

我更喜欢使用以下内容(这是因为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方法找出您应该作为回复发送的内容。