繁体   English   中英

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

[英]Koa, Node.js, Server - How can I get Koa's Router-level middleware function from the Server object?

我想从我在代码中最后创建的服务器对象中调用中间件功能。 我该如何实现? 似乎那里没有很多信息。 我的目标是提取中间件功能并为所有调用保留索引。 当我测试应用程序时,不必真正通过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 }

我想到了。 为了在测试中间件时不使用服务器,您需要使用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));
      (...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM