【问题标题】:Koa, Node.js, Server - How can I get Koa's Router-level middleware function from the Server object?Koa, Node.js, Server - 如何从 Server 对象中获取 Koa 的路由器级中间件功能?
【发布时间】:2018-06-13 20:15:51
【问题描述】:

我想从我最后在代码中创建的 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);

这里有一些日志可能有助于解决这个问题。 控制台日志(服务器):

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 }

【问题讨论】:

    标签: javascript http router middleware koa


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 2021-06-29
      • 2021-04-02
      • 2016-11-06
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 2017-09-01
      相关资源
      最近更新 更多