如何在node.js中设置Content-Type标头

时间:2019-05-09 09:01:23

标签: node.js

我正在node.js中执行以下代码。代码运行良好,但是本教程告诉我们:

  

现在返回并添加具有application / json值的Content-Type标头,然后再次运行请求。您将收到“您发送的   JSON”消息从服务器返回。

1)我不明白如何为该程序设置标题!

2)另外,如果我在运行程序时未设置标头,则应显示消息“服务器需要应用程序/ json”。我没有看到它在任何地方显示。应该在哪里显示?

const express = require('express');
const app = express();

const requireJsonContent = () => {
  return (req, res, next) => {
    if (req.headers['content-type'] !== 'application/json') {
        res.status(400).send('Server requires application/json')
    } else {
      next()
    }
  }
}

app.get('/', (req, res, next) => {
  res.send('Welcome Home');
});

app.post('/', requireJsonContent(), (req, res, next) => {
  res.send('You sent JSON');
})

app.listen(3000);

2 个答案:

答案 0 :(得分:0)

我在您的代码中看到的是,您定义的函数 requireJsonContent 没有参数。因此,您应该在函数中添加(req,res,next)作为参数。此外,在其中,您将返回一个函数而不执行。但是,我认为您不需要该功能,您的代码应如下所示:

app.post('/', (req, res) => {
  if (req.headers['content-type'] !== 'application/json') {
        res.status(400).send('Server requires application/json')
    } else {
        res.send('You sent JSON');
    }
})

答案 1 :(得分:0)

在express 4.x中,您可以使用res.set()res.append()。读取两种方法here之间的差异。