当前位置: 首页 > 软件库 > Web应用开发 > >

express-promise-router

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发
软件类型 开源软件
地区 不详
投 递 者 魏烨熠
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

express-promise-router

A simple wrapper for Express 4's Router that allows middleware to return promises.This package makes it simpler to write route handlers for Express when dealingwith promises by reducing duplicate code.

Getting Started

Install the module with npm

npm install express-promise-router --save

or yarn.

yarn add express-promise-router

express-promise-router is a drop-in replacement for Express 4's Router.

Documentation

Middleware and route handlers can simply return a promise.If the promise is rejected, express-promise-router will call next with thereason. This functionality removes the need to explicitly define a rejectionhandler.

// With Express 4's router
var router = require("express").Router();

router.use("/url", function (req, res, next) {
  Promise.reject().catch(next);
});

// With express-promise-router
var router = require("express-promise-router")();

router.use("/url", function (req, res) {
  return Promise.reject();
});

Calling next() and next("route") is supported by resolving a promise with either "next" or "route". No action is taken if the promise is resolved with any other value.

router.use("/url", function (req, res) {
  // equivalent to calling next()
  return Promise.resolve("next");
});

router.use("/url", function (req, res) {
  // equivalent to calling next('route')
  return Promise.resolve("route");
});

This package still allows calling next directly.

router = require("express-promise-router")();

// still works as expected
router.use("/url", function (req, res, next) {
  next();
});

ES6 Imports

express-promise-router can be imported via ES6 imports. The Routerconstructor is the default export.

import Router from "express-promise-router";
const router = Router();

Async / Await

Using async / await can dramatically improve code readability.

router.get('/url', async (req, res) {
    const user = await User.fetch(req.user.id);

    if (user.permission !== "ADMIN") {
      throw new Error("You must be an admin to view this page.");
    }

    res.send(`Hi ${user.name}!`);
})

Error handling

Just like with regular express.Router you can define custom error handlers.

router.use((err, req, res, next) => {
  res.status(403).send(err.message);
});

Frequently Asked Questions

Cannot read property '0' of undefined

This error may indicate that you call a method that needs a path, without one.Calling router.get (or post, all or any other verb) without a path is notvalid. You should always specify a path like this:

// DO:
router.get("/", function (req, res) {
  res.send("Test");
});

// DON'T:
router.get(function (req, res) {
  res.send("Test");
});

For more information take a look at this comment.

Can i use this on app?

We currently don't support promisifying the app object. To use promises withthe top-level router we recommend mounting a Router on the app object, likethis:

import express from "express";
import Router from "express-promise-router";

const app = express();
const router = Router();
app.use(router);

router.get("/", function (req, res) {
  res.send("Test");
});

Why aren't promise values sent to the client

We don't send values at the end of the promise chain to the client, because thiscould easily lead to the unintended leak of secrets or internal state. If youintend to send the result of your chain as JSON, please add an explicit.then(data => res.send(data)) to the end of your chain or send it in the lastpromise handler.

Contributing

Add unit tests for any new or changed functionality.Lint and test your code using npm test.

Unit tests use mocha andchai.

We use eslint, but styling iscontrolled mostly byprettierwhich reformats your code before you commit. You can manually trigger areformat using npm run-script format.

Release History

See CHANGELOG

Attribution

Licensed under the MIT license.

Initial implementation by Alex Whitney
Maintained by Moritz Mahringer
Contributed to by awesome people

  • express-generator 本文主要分享 通过使用express-generator脚手架 来配置用户接口的响应 app.js: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var logger = require('morga

  • 1. 前言 鉴于之前使用express和koa的经验,最近想尝试构建出一个koa精简版,利用最少的代码实现koa和koa-router,同时也梳理一下Node.js网络框架开发的核心内容。 实现的源代码将会放在文末,配有详细的注释。 2. 核心设计 2.1 API调用 在mini-koa的API设计中,参考koa和koa-router的API调用方式。 Node.js的网络框架封装其实并不复杂,其

  • 介绍 (Introduction) Vue.js is a progressive JavaScript framework for building front-end applications. Coupled with vue-router, we can build high performance applications with complete dynamic routes. Vu

  • express中的使用 安装express-jwt npm install express-jwt 配置express-jwt const expressJwt = require('express-jwt'); app.use(expressJwt({ secret: 'userLogin', // 签名的密钥 algorithms: ["HS256"] // 设置算法(官方文档上没有

 相关资料
  • express-promise An express.js middleware for easy rendering async query. Cases 1. previously app.get('/users/:userId', function(req, res) { User.find(req.params.userId).then(function(user) {

  • 问题内容: 我有一个Node / Express路由功能,该功能在另一个模块中执行Redis调用。我想在一个节点模块中执行复杂的Redis功能,并发送一个简单的回调,说路由模块成功了。Redis调用会执行,但是我无法执行任何同步功能,即使从Redis调用中检索甚至是一个简单的true值。这是我的Redis函数: doctorDB.js 一切都为此目的而努力。现在,我希望将回调发送到Express路

  • 想象一下,你是一位顶尖歌手,粉丝没日没夜地询问你下个单曲什么时候发。 为了从中解放,你承诺(promise)会在单曲发布的第一时间发给他们。你给了粉丝们一个列表。他们可以在上面填写他们的电子邮件地址,以便当歌曲发布后,让所有订阅了的人能够立即收到。即便遇到不测,例如录音室发生了火灾,以致你无法发布新歌,他们也能及时收到相关通知。 每个人都很开心:你不会被任何人催促,粉丝们也不用担心错过单曲发行。

  • 在JavaScript的世界中,所有代码都是单线程执行的。 由于这个“缺陷”,导致JavaScript的所有网络操作,浏览器事件,都必须是异步执行。异步执行可以用回调函数实现: function callback() { console.log('Done'); } console.log('before setTimeout()'); setTimeout(callback, 1000)

  • Promise模式 我们已经隐含地看到了使用Promise链的顺序模式(这个-然后-这个-然后-那个的流程控制),但是我们还可以在Promise的基础上抽象出许多其他种类的异步模式。这些模式用于简化异步流程控制的的表达——它可以使我们的代码更易于推理并且更易于维护——即便是我们程序中最复杂的部分。 有两个这样的模式被直接编码在ES6原生的Promise实现中,所以我们免费的得到了它们,来作为我们其