node.js - 如何在 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);
解决方案
我在您的代码中看到的是,您定义的函数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');
}
})
推荐阅读
- magento - 如何在管理端插件的自定义模块中添加重置密码功能?
- algorithm - 如果你有一个 O(n^3) 的算法,那么你可以用一台速度快 10 倍的计算机同时处理多少个元素?
- c - 声明计数器时比较 uint8_t 与 uint16_t
- c - 创建一个使用 srand 和 rand 生成随机数的函数
- javascript - 复制链接时如何添加事件和更改?
- express - Heroku 部署错误:npm ERR!主机密钥验证失败。NextJS/ExpressJS 应用程序
- python - 重塑 Pandas 数据框,在 Python 中的多列上重复项目计数
- reactjs - React Tinymce Quickbar 添加字体大小选项作为输入字段
- javascript - 有没有办法将我自己的帐户用于 twitch 聊天机器人?
- python - 将具有重复值的列表转换为数据框