0

我有一个使用koa和构建的应用程序koa-router。当supertest我遇到问题测试路由时,该content-type响应标头始终为application/json; charset=utf-8.

const app = koa();
router
    .get('/img', function *(next) {
      this.type = 'image/png';
      // this.set('Content-Type', 'image/png'); 
      // this.set('content-type', 'image/png');
      this.body = renderImage();
    });

app
  .use(router.routes())
  .use(router.allowedMethods());


describe('Routes', () => {

  it('should handle /tiles/*/*/*/* requests', (done) => {
    request(http.createServer(app.callback()))
      .get('/img')
      .expect(200)
      .expect('Content-Type', 'image/png')
      .end(function (err, res) {
        console.log(res.res.headers);
        if (err) return done(err);

        expect(renderImage).to.be.called;
        done();
      });
  });

测试如何失败:

错误:预期为“image/png”的“Content-Type”,在 Test._assertFunction 的 Test._assertHeader (node_modules/supertest/lib/test.js:215:12) 处得到“application/json; charset=utf-8” (node_modules/supertest/lib/test.js:247:11) 在 Test.assert (node_modules/supertest/lib/test.js:148:18) 在 Server.assert (node_modules/supertest/lib/test.js:127 :12) 在 emitCloseNT (net.js:1525:8)

通过以下方式记录的内容console.log(res.res.headers)

{ 'content-type': 'application/json; charset=utf-8',
'content-length': '2',
date: 'Wed, 09 Mar 2016 10:15:37 GMT',
connection: 'close' }

但是,如果我从浏览器向提供的路由发出请求,则content-type标头会正确更改:

Connection:keep-alive
Content-Length:334
Content-Type:image/png
Date:Wed, 09 Mar 2016 10:15:01 GMT

既不this.set('Content-Type', 'image/png');也不 this.set('content-type', 'image/png');改变情况。

它是一个错误吗?有没有人遇到过同样的问题?

4

1 回答 1

2

有几件事可以尝试:

实际上是this.body = renderImage()把身体设置为nullorundefined吗?
在查看响应对象content-type的 Koa.js 代码时,如果 body 设置为nullor ,看起来 koa 正在删除标头undefined

renderImage()对象的返回值吗?如果是这样,它是缓冲区还是流?当body设置 koa 尝试检测响应的内容类型应该是什么。如果它不是string,Bufferstream, koa强制content-type标题为application/json.

于 2016-03-10T16:23:33.580 回答