javascript - 如果与普通 NodeJS 服务器中的给定模式不匹配,如何正确检查 HTTP 请求正文并拒绝它?
问题描述
我正在构建一个仅使用 nodeJS 库和方法的服务器,但我无法检查请求正文格式并立即使用客户端错误状态代码类型 (400-499) 进行响应。
以下代码是我的服务器支持的一种请求类型的控制器的 js 文件(我使用的是 MVC 类型架构):
const { createNews } = require('../useCases/postNewsUseCase'); //useCase file to which the request proceeds if its in good format
const postNews = (req, res) => {
if (req.method !== 'POST') { //tests if request method is correct
res.writeHead(405, { 'Contet-type': 'text/plain' });
res.end();
}
let data = '';
req.on('data', chunk => {
data += chunk;
})
req.on('end', () => {
const newsBody = JSON.parse(data);
if (Object.keys(newsBody).toString() !== ['title','content','category'].toString()){
res.writeHead(400, { 'Contet-type': 'text/plain' });
res.end();
} // tests if the request body format matches the expected
for (let field in newsBody) {
if ((/^\s*/).test(newsBody[field])){
res.writeHead(400, { 'Contet-type': 'text/plain' });
res.end(); // tests if any property is not provided/blank
}
}
createNews(newsBody); //sends the request to the next level which will interact with the DB
res.end();
});
}
module.exports = {
postNews
}
问题是,如果发送了类似以下(错误格式)的请求正文,服务器将继续进入 useCase 级别,而不是按照我的测试中指定的结束客户端和服务器之间的通信:
{
"title":"titulo",
"content":"conteudo"
}
谁能帮我?我是否滥用 res.end() 来结束通信并返回服务器响应?
解决方案
您可以使用 Joi 库。https://github.com/sideway/joi
使用示例。
{
"title": "This is supposed to be a title",
"content": "There should be some content here."
}
const schema = Joi.object({
title: Joi.string().min(8).max(30).required(),
content: Joi.string().min(24).max(255).required(),
});
推荐阅读
- c++ - std::basic_string 作为函数模板的参数不能从 const char* 推导出来
- sql-server - 用历史平均值替换月值
- google-sheets - 谷歌表格查询=真
- python - 使用队列实现链表:Python
- git - 如何将“origin/master”添加到本地仓库(可能还有远程仓库),尽管我已经可以推送到远程
- html - 所选选项中的平均答案(按字母值)
- python - 用 numpy 数组/pandas 数据框中最接近的记录替换每条记录
- rust - Rust 宏:单元类型?
- snowflake-cloud-data-platform - 角色创建问题
- mysql - 无状态 bean 内 JPQL 数据中的错误