如何解决如果与普通 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
}
问题是,如果发送了类似于以下(错误格式)的请求正文,则服务器无论如何都会继续使用用例级别,而不是按照我的测试中的规定终止客户端和服务器之间的通信:
{
"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(),});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。