node-fetch 接收到空体

node-fetch receives empty body

我正在为一个简单的 NodeJS 应用程序编写单元测试,但由于某种原因我无法检索响应正文。它获得正确的响应代码(成功请求为 200 或无效请求为 422)但正文似乎是空的。此外,当我用 httpie 发出完全相同的请求时,它就像魅力一样。日志记录还显示控制器按预期工作。

欢迎提出任何想法或建议。

控制器部分如下:

function register (req, res) {
  return _findUser({email: req.body.email})
    .then(user => {
      if (user) {
        console.log('EMAIL TAKEN');
        return Promise.reject({message: 'This email is already taken'});
      }

      let params = _filterParams(req.body);
      if (_isRegistrationValid(params)) {
        console.log('REGISTRATION VALID');
        return params;
      } else {
        console.log('PARAMS INVALID');
        return Promise.reject({message: 'Params invalid'});
      }
    })
    .then(_createUser)
    .then(_generateToken)
    .then(token => {
      console.log('SENDING TOKEN');
      console.log(token);
      res.send({token: token});
    })
    .catch(error => {
      console.log('CATCH ERROR');
      res.status(422).send(error);
    });
}

测试部分如下:

it ('Returns token when data is valid', done => {
  fetch(`http://localhost:${testPort}/api/register`, {
    headers: {'Content-Type': 'application/json'},
    method: 'POST',
    body: JSON.stringify({email: 'test@test.com', password: 'password', confirmPassword: 'password'})
  })
    .then(response => {
      assert(response.ok); // this part works ok
      expect(response.body.token).to.exist; // this part fails
      done();
    })
    .catch(done);
});

这是 httpie 输出:

kpr$ http post localhost:4000/api/register email="rest@test.com" password="password" confirmPassword="password"
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 941
Content-Type: application/json; charset=utf-8
Date: Sat, 08 Oct 2016 11:39:30 GMT
ETag: W/"3ad-uBdW+HLbY7L2gb65Y+zptQ"
X-Powered-By: Express

{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9_long_token_string_2M"
}

测试输出如下:

REGISTRATION VALID
_createUser
(node:70495) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
_generateToken
SENDING TOKEN
eyJhbGciOiJIU_long_token_string_lmYA

  0 passing (160ms)
  2 pending
  1 failing

  1) Authorization Registration Returns token when data is valid:
     AssertionError: expected undefined to exist
      at fetch.then.response (test/auth-controller-spec.js:57:41)
      at process._tickCallback (internal/process/next_tick.js:103:7)

fetch() 中打印响应主体显示了一些巨大的对象:

PassThrough {
  _readableState:
   ReadableState {etc...}
}

您需要尝试 response.json() 而不是 response.ok,这将 return 以适当的方式响应您的情况。

希望对您有所帮助!