如果与普通 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(),});