首页 > 解决方案 > 如何在 node.js 中设置 Content-Type 标头

问题描述

我在 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);

标签: node.js

解决方案


我在您的代码中看到的是,您定义的函数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');
    }
})

推荐阅读