设置当前的上下文

@param {Object} req 请求对象
@param {Object} res 响应对象
@param {Function} next 执行下一个中间件
977278
function setContext(req, res, next) {
    currentContext = {req: req, res: res};
    next();
}
1069713
function AssetHandler(req, res, next, local = false) {
            const parsedUrl = url.parse(req.url);
            // Check if we have an asset for that url defined.
            /** @type {Asset} */
            const asset = self.assetBundle.assetForUrlPath(parsedUrl.pathname);

            if (!asset) return next();

            const processors = () => (
                addSourceMapHeader(asset, res),
                addETagHeader(asset, res),
                addCacheHeader(asset, res, req.url)
            );

            if (local) {
                return createStreamProtocolResponse(asset.getFile(), res, processors);
            }
            return send(
                req,
                encodeURIComponent(asset.getFile()),
                { etag: false, cacheControl: false }
            )
                .on('file', processors)
                .pipe(res);
        }
1079457
function(req, res, next) {
    Tag.findOne({ name: req.params.name }, function(err, tag) {
      if (err) return next(err);
      if (!tag) return res.json(404, { error: 'failed to load tag ' + req.params.name });
      req.tag = tag;
      next();
    });
  }
494381
function redirectToNext(req, res) {
  var redirectTo = req.session.next || '';
  req.session.next = null; // Null it so that we do not use it again.
  res.redirect(redirectTo);
}
1262325
function getSubmissionFile(req, res, next) {
  var params = {"_id": req.params.fileId};
  logger.debug("Middleware getSubmissionFile ", {params: params});
  forms.getSubmissionFile(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next));
}
862050
function serveErr(_req, res, next) {
    return async function (err) {
        if (err.message === 'next') {
            return next();
        }
        console.log('ERROR', err);
        console.log('STACK', err.stack);
        let text = 'ERROR' + (err.code ? ' ' + err.code : '') + ': ' + err.message;
        exports.globalOpts.serveErr.propertiesWhiteList.forEach(function (attrName) {
            if (attrName in err) {
                text += '\n' + attrName + ': ' + JSON.stringify(err[attrName]);
            }
        });
        if (exports.globalOpts.serveErr.sendStack) {
            text += '\n------------------\n' + err.stack;
        }
        if (!res.headersSent) {
            let buf = new Buffer(text);
            let length = buf.length;
            res.writeHead(err.status || 400, {
                'Content-Length': length,
                'Content-Type': 'text/plain; charset=utf-8'
            });
        }
        else {
            text += "\n</script>\n<pre>\n------------------------------------\n" + text;
        }
        res.end(text);
    };
}
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
455807
function transform(req, res, next) {
    const state = res.state;
    const body = state.body;
    const type = typeof body;
    const isBuffer = body instanceof Buffer;
    let contentType;

    // error conversion
    if (body instanceof Error) {
        res.log('transform', 'Converting Error to response');
        res.status(500).body(httpStatus[500]).set('content-type', 'text/plain');

    // buffer conversion
    } else if (isBuffer) {
        res.log('transform', 'Converting Buffer to base64 string');
        res.body(body.toString('base64'));
        contentType = 'application/octet-stream';

    // object conversion
    } else if (type === 'object') {
        res.log('transform', 'Converting object to JSON string');
        res.body(JSON.stringify(body));
        contentType = 'application/json';

    // not string conversion
    } else if (type !== 'string') {
        res.log('transform', 'Converting ' + type + ' to string');
        res.body(String(body));
        contentType = 'text/plain';

    } else {
        contentType = 'text/html';
    }

    // set content type if not yet set
    if (!state.headers.hasOwnProperty('content-type') && contentType) {
        res.log('transform', 'Set content type');
        res.set('Content-Type', contentType);
    }

    next();
}
125450
function(err, req, res, next) {
    if (err) {
        var url = req.url || '';

        log.debug(req.method, req.headers);
        log.error(('Requested url: ' + url).red, ('Error: ' + err.stack).red);

        if (req.xhr) {
            res.status(500).json({msg: 'Server error'});
        } else {
            res.status(500).send('Server error');
        }
    } else {
        next();
    }
}
157041
function(req,res,next){
  var token = req.get('X-OOSE-Token')
  if(!token || user.session.token !== token){
    res.status(401)
    res.json({error: 'Invalid session'})
  } else {
    req.session = user.session
    next()
  }
}
205423
function (req, res, next) {
      var id
      try { id = decodeURIComponent(req.url.substring(5)) }
      catch (_) { id = req.url.substring(5) }
      if(req.url.substring(0, 5) !== '/msg/' || !ref.isMsg(id)) return next()

      sbot.get(id, function (err, msg) {
        if(err) return next(err)
        send(res, {key: id, value: msg})
      })
    }
47126
function list(req, res, next) {
  var notStats = req.query && (req.query.notStats === 'true' || req.query.notStats === true);
  var opts = _.extend(req.connectionOptions, { notStats: notStats });

  logger.debug("List Forms Middleware ", opts);
  forms.getAllForms(opts, formsResultHandlers(constants.resultTypes.forms, req, next));
}
82856
function (res, args) {
            // callback args preparation
            var requestObject = args.requestObject, actionQueuing = args.actionQueuing;
            var id = args.id, senderObject = args.senderObject;
            // var cb = args.cb, session = args.session, requestHandler = args.requestHandler

            // starts right now for next item in action queuing
            if (actionQueuing) {
                actionQueuing.handleNextRequest(id);
            }

            // updated resources
            var newRes = {
                requestUrl : res.url,
                requestObject : requestObject,
                responseXML : res.responseXML,
                responseText : res.responseText,
                responseJSON : res.responseJSON,
                status : res.status, // http status (e.g.: 404)
                error : res.error, // contains error message

                // Should we stop supporting the following properties ?
                // These properties can be set by IO filters (through the sender object) to bypass the response handler
                data : senderObject.responseData,
                errorData : senderObject.responseErrorData
            };

            args.res = newRes;

            this._processOnResponse(args);
        }
1041759
function requestHandler(req, res, next) {
  const params = req && req.params;
  const start = Date.now();
  let source;
  let opts;

  return Promise.try(() => {
    source = core.getPublicSource(params.src);

    if (!_.contains(source.formats, params.format)) {
      throw new Err('Format %s is not known', params.format).metrics('err.req.format');
    }

    params.z = core.validateZoom(params.z, source);
    params.scale = core.validateScale(params.scale, source);

    params.x = checkType.strToInt(params.x);
    params.y = checkType.strToInt(params.y);
    if (
      !qidx.isValidCoordinate(params.x, params.z) || !qidx.isValidCoordinate(params.y, params.z)
    ) {
      throw new Err('x,y coordinates are not valid, or not allowed for this zoom').metrics('err.req.coords');
    }

    opts = {
      z: params.z,
      x: params.x,
      y: params.y,
    };
    if (params.format !== 'pbf') {
      // Ensure that PNGs are not 32bit
      // TODO: this should be source-configurable
      opts.format = params.format === 'png' ? 'png8:m=h' : params.format;
      if (params.scale) {
        opts.scale = params.scale;
      }
    }
    if (req.query && req.query.lang) {
      if (!langCodeRe.test(req.query.lang)) {
        throw new Err('lang param is not valid').metrics('err.req.lang');
      }
      opts.lang = req.query.lang;
    }

    // fixme: Force all tiles to be treated as vector
    opts.treatAsVector = true;

    return source.getHandler().getAsync(opts);
  }).then((result) => {
    let mx;

    core.setResponseHeaders(res, source, result.headers);

    if (params.format === 'json') {
      // Allow JSON to be shortened to simplify debugging
      res.json(filterJson(req.query, result.data));
    } else {
      res.send(result.data);
    }

    mx = util.format('req.%s.%s.%s', params.src, params.z, params.format);
    if (params.scale) {
      // replace '.' with ',' -- otherwise grafana treats it as a divider
      mx += `.${params.scale.toString().replace('.', ',')}`;
    }
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
1168836
function(req, res) {
            var updateJson = {};
            var updateSelector = {};

            //Request database structure
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table , function (err, columns) {
                if (err) return sendError(res,err.code);

                //Check if the request is provided an select value
                if (typeof req.params.id === "undefined") {
                    return sendError(res,'Please specify an selector value for the fields ');
                } else {
                    updateSelector.value = req.params.id;
                    updateSelector.field = findPrim(columns,req.query[settings.paramPrefix + 'field']);
                }

                //If the user only wants to update files
                if( Object.keys(req.body).length == 0) {
                    req.body = req.files;
                }
                var value;
                var iterator = function (i) {
                    if (i >= columns.length || (typeof req.body.length === "undefined" && typeof req.files.length !== "undefined")) {
                        if(JSON.stringify(updateJson) !== '{}') {
                            updateIntoDB();
                        } else {
                            return sendError(res,'No Data received!');
                        }
                        return;
                    }
                    var dbField = columns[i];
                    var field = dbField.Field;
                    //Check if the current checked field is set
                    if(typeof req.body[field] !== "undefined" || (dbField.Default == 'FILE' && typeof req.files[field] !== "undefined") ) {
                        //First check if the field is required
                        if(dbField.Null == 'NO' && dbField.Extra != 'auto_increment') {
                            value = checkIfSentvaluesAreSufficient(req,dbField);
                            if(value !== false) {
                                updateJson[field] = value;
                                iterator(i + 1);
                            } else {
                                return sendError(res,"Not all 'NOT NULL' fields are filled ("+ field +" is missing)");
                            }
                        }  else {
                            //Check for not required fields
                            //Skip auto_incremented fields
                            if(dbField.Extra === 'auto_increment') {
                                iterator(i + 1);
                            } else {
                                //Check if the field was provided by the client
                                var defined = false;
                                if(dbField.Default == "FILE") {
                                    if(req.files.hasOwnProperty(dbField.Field)) {
                                        defined = true;
                                    }
                                } else {
                                    if(typeof req.body[field] !== "undefined") {
                                        defined = true;
                                    }
                                }

                                //If it was provided, check if the values are okay
                                if(defined) {
                                    value = checkIfSentvaluesAreSufficient(req,dbField);
                                    if(value !== false) {
                                        updateJson[field] = value;
                                        iterator(i + 1);
                                    } else {
                                        if(dbField.Default == "FILE") {
                                            return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
                                        } else {
                                            return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
                                        }
                                    }
                                } else {
                                    //If not, don't mind
                                    iterator(i + 1);
                                }
                            }
                        }
                    } else {
                        iterator(i + 1);
                    }
                };

                iterator(0); //start the async "for" loop

                function updateIntoDB() {
                    //Yaaay, alle Tests bestanden gogo, insert!
                    lastQry = connection.query('UPDATE ?? SET ? WHERE ?? = ?', [req.params.table , updateJson, updateSelector.field, updateSelector.value] , function (err) {
                        if (err) return sendError(res,err.code);
                        sendSuccessAnswer(req.params.table , res, req.params.id, updateSelector.field);

                    });
                }
            });
        }
1370338
function (req, res, next) {
    if (vulpejs.app.security.ignore) {
      exports.auth.checkAfter(req, res, next);
      return;
    }
    if (!req.cookies.appLanguage || req.cookies.appLanguage === 'undefined') {
      res.cookie('appLanguage', 'pt');
    }
    var skip = false;
    for (var i = 0, len = loginSkip.length; i < len; ++i) {
      var skipUri = vulpejs.app.root.context + loginSkip[i];
      if (skipUri === req.originalUrl || (skipUri !== '/' && req.originalUrl.indexOf(skipUri) === 0)) {
        skip = true;
        break;
      }
    }
    if (!req.isAuthenticated()) {
      if (!skip) {
        req.session['redirect-to'] = req.originalUrl;
        res.redirect(vulpejs.app.root.context + '/login');
        return;
      }
      exports.auth.checkAfter(req, res, next);
    } else {
      var roles = req.session['user-roles'];
      if (skip || !roles || roles.length === 0 || !vulpejs.app.security.routes || vulpejs.app.security.routes.length === 0) {
        exports.auth.checkAfter(req, res, next);
        return;
      }
      var hasRouteRoles = function (route) {
        if (route === '') {
          return false;
        }
        var roleExists = !route.roles || route.roles.length === 0;
        if (!roleExists) {
          for (var i = 0, len = roles.length; i < len; ++i) {
            if (route.roles.indexOf(roles[i]) !== -1) {
              roleExists = true;
              break;
            }
          }
        }
        return roleExists;
      };
      var routeWildcard = '';
      var requestedRoute = '';
      var roleExists = false;
      var routeExists = false;
      var routes = vulpejs.app.security.routes.length;
      var uriCheck = function (value) {
        return (value === '/' && req.originalUrl === value) || (value !== '/' && req.originalUrl.indexOf(value) === 0);
      };
      for (var i = 0; i < routes; ++i) {
        var route = vulpejs.app.security.routes[i];
        if (route.uris && Array.isArray(route.uris)) {
          for (var j = 0; j < route.uris.length; ++j) {
            if (uriCheck(route.uris[j])) {
              requestedRoute = route;
              break;
            }
          }
        } else if (route.uri === '/**') {
          routeWildcard = route;
        } else if (uriCheck(route.uri)) {
          requestedRoute = route;
        }
        if (requestedRoute) {
          break;
        }
      }
      if (((requestedRoute === '' && routeWildcard === '') || hasRouteRoles(requestedRoute)) || (routeWildcard !== '' && hasRouteRoles(routeWildcard))) {
        exports.auth.checkAfter(req, res, next);
      } else {
        res.status(403);
        exports.render(res, 'error', {
          ui: {
            controller: 'Error',
          },
          error: {
            status: 403,
            message: 'Forbidden',
          },
        });
      }
    }
  }
745003
function(req, res, next) {
			res.set('XX-Powered-By', 'Restpress');
			req.resource = self;
			req.actionName = actionName;
			req.action = action;
			next();
		}