首页 > 解决方案 > 如果与普通 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() 来结束通信并返回服务器响应?

标签: javascriptnode.jshttpmodel-view-controllerhttpserver

解决方案


您可以使用 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(),
 });

推荐阅读