Koa,Node.js,Server - 如何从Server对象获取Koa的路由器级中间件功能?

时间:2018-06-13 20:15:52

标签: javascript http router middleware koa

我希望从我在代码中最后创建的 server 对象中调用 middleware 函数。我怎样才能做到这一点?似乎没有很多信息。我的目标是提取中间件函数并为所有调用保留索引。当我测试应用程序时,我不必实际调用http请求。

const app = new Koa();
  const router = new Router();

  async function middleware(context: Koa.Context) {
    // the client is requesting a specific statusCode to be returned
    if (context.query.status !== undefined) {
      context.status = parseInt(context.query.status, 10);
      if (context.query.body !== undefined) {
        try {
          context.body = JSON.parse(context.query.body);
        } catch (e) {
          context.body = context.query.body;
        }
      }
      return;
    }
    // put all the inbound x-headers in the response, prepended with 'ping.'
    Object.keys(context.headers).forEach(header => {
      if (header.toLowerCase().startsWith('x-')) {
        context.response.set(`x-ping-${header.slice(2)}`, context.headers[header]);
      }
    });

    context.body = {
      ping: (context.request as any).body
    };
    context.status = 200;
  }
  router.head('/ping', middleware);
  router.get('/ping', middleware);
  router.del('/ping', middleware);
  router.put('/ping', middleware);
  router.post('/ping', middleware);
  router.patch('/ping', middleware);

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

  const port = await findPort();
  const server = app.listen(port);

以下是一些可能有助于解决此问题的日志。 的console.log(服务器):

Server {
  domain: null,
  _events: 
   { request: [Function: handleRequest],
     connection: [ [Function: connectionListener], [Function] ] },
  _eventsCount: 2,
  _maxListeners: undefined,
  _connections: 0,
  _handle: 
   TCP {
     reading: false,
     owner: [Circular],
     onread: null,
     onconnection: [Function] },
  _usingWorkers: false,
  _workers: [],
  _unref: false,
  allowHalfOpen: true,
  pauseOnConnect: false,
  httpAllowHalfOpen: false,
  timeout: 120000,
  keepAliveTimeout: 5000,
  _pendingResponseData: 0,
  maxHeadersCount: null,
  _connectionKey: '6::::49612',
  [Symbol(IncomingMessage)]: 
   { [Function: IncomingMessage]
     super_: 
      { [Function: Readable]
        ReadableState: [Function: ReadableState],
        super_: [Function],
        _fromList: [Function: fromList] } },
  [Symbol(ServerResponse)]: { [Function: ServerResponse] super_: { [Function: OutgoingMessage] super_: [Function] } },
  [Symbol(asyncId)]: 3220 }

1 个答案:

答案 0 :(得分:0)

我知道了。为了在测试中间件时不使用服务器,您需要使用app.callback()。

代码预览:

 const socket: net.Socket = new net.Socket();
 const req = new http.IncomingMessage(socket);
 req.url = url;
 req.method = method;
 req.headers = headers; // (whatever more you need to set)

 if (json) {
     (req as any).body = json;
 }
 const res = new http.ServerResponse(req);
 const cb = callback(app);
 try {
     response = (await cb(req, res));
      (...)