首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >node/express中间件测试- res.send

node/express中间件测试- res.send
EN

Stack Overflow用户
提问于 2018-03-08 07:11:30
回答 1查看 505关注 0票数 0

我正在尝试为以下中间件编写一个测试,以防止JSON漏洞:

代码语言:javascript
复制
/**
* JSON vulnerability protection - prepend the data with ")]},\n", 
*/
function protectJSON(req, res, next) {
  res.send = (...args) => _prependAndSend(res, args);
  return next();
}

module.exports = {
 protectJSON,
};

function _prependAndSend(res, args) {
  let body = args[0];
  const statusCode = args[1];
  const contentType = res.getHeader('Content-Type');
  // EDIT: added _send
  const _send = res.send;

  console.log('body', JSON.stringify(body));

  if (contentType && contentType.indexOf('application/json') !== -1) {
    _send.call(res, `)]}',\n${body}`);
  } else {
   _send.apply(res, args);
  }
}

所以我写了下面的测试,但当我运行它时,我有一个疯狂的循环(res.send被无休止地调用)。

代码语言:javascript
复制
describe('Test suite for middlewares.protectJSON', () => {
  let nextMock;
  let responseStub;

  beforeEach(() => {
    nextMock = sinon.stub();
    responseStub = {
      getHeader: sinon.stub(),
    };
  });

  it('should not prefix content type other than json', () => {
    protectJSON(null, responseStub, nextMock);
    responseStub.send({ data: 'test' });

    expect(responseStub.send).to.have.been.calledWith( data: 'test' });
  });
});

当我运行测试时,我得到

代码语言:javascript
复制
body {"data":"test-data"}
body {"data":"test-data"}
body {"data":"test-data"}
body {"data":"test-data"}
// more logging
body {"data":"test-data"}

我不知道为什么它会为了修复它而表现成这样。感谢您的帮助。

EN

回答 1

Stack Overflow用户

发布于 2018-03-13 02:15:31

修复了它

代码语言:javascript
复制
function protectJSON(req, res, next) {
  const _send = res.send;
  res.send = (...args) => _prependAndSend(res, _send, args);
  return next();
}

基本上,我从_prependAndSend方法中删除了_send的声明,而是在protectJSON方法中声明它,然后将其作为参数传递给prependAndSend方法。

代码语言:javascript
复制
function _prependAndSend(res, _send, args) {
  let body = args[0];
  const statusCode = args[1];
  const contentType = res.getHeader('Content-Type');

  if (contentType && contentType.indexOf('application/json') !== -1) {
    _send.call(res, `)]}',\n${body}`);
  } else {
    _send.apply(res, args);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49162786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档