當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript Router.post方法代碼示例

本文整理匯總了TypeScript中express.Router.post方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Router.post方法的具體用法?TypeScript Router.post怎麽用?TypeScript Router.post使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在express.Router的用法示例。


在下文中一共展示了Router.post方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: Router

export const transaction = ({ db }: { db: any }) => {
	const api: Router = Router();

	/**
	 * Starts the purchasing process with XEM
	 */
	api.post('/initiate-xem-purchase', vInitiateXEMPurchase, async (req: Request, res: Response) => {
		try {
			const product = await findById<Product>(DB_PRODUCTS, req.body[KEY_PRODUCT_ID]);
			if (!product.isEnabled) { return res.status(409).json(new Error('Product temporarily locked.')); }
			res.send(await initiateXEMPurchaseHandler(req));
		} catch (err) {
			res.status(409).json(err);
		}
	});

	/**
	 * Starts the purchasing process with Coinbase
	 */
	api.post('/initiate-coinbase-purchase', vInitateCoinbasePurchase, async (req: Request, res: Response) => {
		try {
			const product = await findById<Product>(DB_PRODUCTS, req.body[KEY_PRODUCT_ID]);
			if (!product.isEnabled) { return res.status(409).json(new Error('Product temporarily locked.')); }
			res.send(await createCoinbaseCharge(req.body[KEY_TOKEN_RECIPIENT_ADDRESS], req.body[KEY_PRODUCT_ID]));
		} catch (err) {
			res.status(409).json(err);
		}
	});

	return api;
};
開發者ID:joseabril25,項目名稱:nem-coinbase-token-sale-api,代碼行數:31,代碼來源:transaction.ts

示例2: createRoutes

export function createRoutes(router: Router, auth: RequestHandler, setRouteVar: RequestHandler): void {
  // list route
  router.get('/', setRouteVar, list)

  // single entry route
  router.get('/:slug', setRouteVar, get)

  // comment route
  router.get('/:slug/comments', setRouteVar, comments)
  
  // action list route
  router.get('/:slug/:sublist', setRouteVar, sublist)
  
  // check if slug available
  router.post('/unique', setRouteVar, isUnique)

  // create route
  router.post('/', auth, setRouteVar, create)

  // create gallery
  router.put('/:slug/gallery', auth, setRouteVar, upload)

  // clear gallery
  router.delete('/:slug/gallery', auth, setRouteVar, clear, update)

  // update route
  router.patch('/:slug', auth, setRouteVar, update)

  // delete route
  router.delete('/:slug', auth, setRouteVar, remove)  
}
開發者ID:yeegr,項目名稱:SingularJS,代碼行數:31,代碼來源:ContentController.ts

示例3: constructor

 constructor(){
   this.router = Router();
   this.controller = new StockController();
   this.router.get("/soldtrades", (req: Request, res: Response) => this.getSoldTrades(req, res));
   this.router.get("/holdingstocks", (req: Request, res: Response) => this.getHoldingStocks(req, res));
   this.router.post("/", upload.single('file'), (req: Request, res: Response) => this.uploadStockTransactionsCSV(req, res));
   this.router.post("/import", (req: Request, res: Response) => this.importStockTransactions(req, res));
 }
開發者ID:kongbb,項目名稱:MyFinance,代碼行數:8,代碼來源:stock.route.ts

示例4: constructor

 constructor(){
     this.router = Router();
     this.controller = new TransactionController();
     this.router.get("/:type", (req: Request, res: Response) => this.getTransactions(req, res));
     this.router.get("/:type/categories", (req: Request, res: Response) => this.getCategories(req, res));
     this.router.post("/transaction", (req: Request, res: Response) => this.postTransaction(req, res));
     this.router.post("/", upload.single('file'), (req: Request, res: Response) => this.uploadTransactionsCSV(req, res));
     this.router.delete("/:id", (req: Request, res: Response) => this.deleteTransaction(req, res));
 }
開發者ID:kongbb,項目名稱:MyFinance,代碼行數:9,代碼來源:transactions.route.ts

示例5: gameRouter

export function gameRouter(gameHandler: GameHandlerService): Router {
  let router: Router = Router();

  router.post('/',
    [
      body('title_ko').isString().not().isEmpty(),
      body('title_en').isString().not().isEmpty(),
      body('players').isArray(),
      body('players.*').isInt().toInt(),
      body('box.width').isInt().toInt(),
      body('box.height').isInt().toInt(),
      body('box.depth').isInt().toInt(),
      body('setting.width').isInt().toInt(),
      body('setting.height').isInt().toInt(),
    ],
    handleValidationResult,
    gameHandler.createGame.bind(gameHandler)
  );

  router.get('/:gid',
    [param('gid').isNumeric().not().isEmpty()],
    handleValidationResult,
    gameHandler.getGame.bind(gameHandler)
  );

  return router;
}
開發者ID:cuponthetop,項目名稱:bg-hub,代碼行數:27,代碼來源:game.ts

示例6: setupRoutes

  setupRoutes() {
    const router = this.router
    const svc = this.licenseService

    router.get(
      '/status',
      this.asyncMiddleware(async (req, res) => {
        if (process.BOTPRESS_EDITION === 'ce') {
          return sendSuccess(res, 'License status', { edition: process.BOTPRESS_EDITION })
        }

        const status = await svc.getLicenseStatus()
        const fingerprint = await svc.getFingerprint('machine_v1')
        let info: LicenseInfo | undefined
        try {
          info = await svc.getLicenseInfo()
        } catch (err) {}

        return sendSuccess(res, 'License status', {
          fingerprint,
          edition: process.BOTPRESS_EDITION,
          license: info,
          ...status
        })
      })
    )

    router.post(
      '/update',
      this.asyncMiddleware(async (req, res) => {
        const result = await svc.replaceLicenseKey(req.body.licenseKey)
        if (!result) {
          throw new InvalidLicenseKey()
        }

        return sendSuccess(res, 'License Key updated')
      })
    )

    router.post(
      '/refresh',
      this.asyncMiddleware(async (req, res) => {
        await svc.refreshLicenseKey()
        return sendSuccess(res, 'License refreshed')
      })
    )
  }
開發者ID:seffalabdelaziz,項目名稱:botpress,代碼行數:47,代碼來源:license.ts

示例7: init

    public init() {
        this.router.get('/boards', function (req, res) {
            board.find({}, function (err, boards) {
                res.json(boards);
            });
        });

        this.router.post('/newBoard', function (req, res) {
            let newBoard = new board(req.body);
            newBoard.save(function (err) {
                if (err) {
                    res.send(err);
                }
                res.json({
                    success: true,
                    message: 'Board created successfully',
                });
            });
        });

        this.router.delete('/delete/:id', function (req, res) {
            board.findById(req.params.id, (err, responseByID) => {
                responseByID.remove(req.body, (err) => {
                    if (err) {
                        res.status(500).send(err);
                    }
                    board.find((err) => {
                        if (err) {
                            res.status(500).send(err)
                        }
                        res.json({
                            success: true,
                            message: 'Removed!',
                        });
                    });
                });
            });
        });

        this.router.put('/update/:id', function (req, res) {
            board.findById(req.params.id, (err, responseByID) => {
                responseByID.update(req.body, (err) => {
                    if (err) {
                        res.status(500).send(err);
                    }
                    board.find((err) => {
                        if (err) {
                            res.status(500).send(err)
                        }

                        res.json({
                            success: true,
                            message: 'Board update successfully'
                        });
                    });
                });
            });
        });
    }
開發者ID:rafaeldmpacheco,項目名稱:tagarela-backend,代碼行數:59,代碼來源:board-router.ts

示例8: setupRoutes

  setupRoutes() {
    this.router.get(
      '/pending',
      this._checkTokenHeader,
      this._needPermissions('read', 'bot.ghost_content'),
      async (req, res) => {
        res.send(await this.ghost.forBot(req.params.botId).getPending())
      }
    )

    this.router.get(
      '/export',
      this._checkTokenHeader,
      this._needPermissions('read', 'bot.ghost_content'),
      async (req, res) => {
        const tarball = await this.ghost.forBot(req.params.botId).exportArchive()
        const name = 'archive_' + req.params.botId.replace(/\W/gi, '') + '_' + Date.now() + '.tgz'
        res.writeHead(200, {
          'Content-Type': 'application/tar+gzip',
          'Content-Disposition': `attachment; filename=${name}`,
          'Content-Length': tarball.length
        })
        res.end(tarball)
      }
    )

    const archiveUploadMulter = multer({
      limits: {
        fileSize: 1024 * 1000 * 100 // 100mb
      }
    })

    // TODO WIP Partial progress towards importing tarballs from the UI
    // this.router.get(
    //   '/import',
    //   this.checkTokenHeader,
    //   this.needPermissions('write', 'bot.ghost_content'),
    //   archiveUploadMulter.single('file'),
    //   async (req, res) => {
    //     const buffer = req['file'].buffer
    //     const botId = req.params.botId
    //     await this.ghost.forBot(botId).importArchive(buffer)
    //     res.sendStatus(200)
    //   }
    // )

    // Revision ID
    this.router.post(
      '/revert',
      this._checkTokenHeader,
      this._needPermissions('write', 'bot.ghost_content'),
      async (req, res) => {
        const revisionId = req.body.revision
        const filePath = req.body.filePath
        await this.ghost.forBot(req.params.botId).revertFileRevision(filePath, revisionId)
        res.sendStatus(200)
      }
    )
  }
開發者ID:seffalabdelaziz,項目名稱:botpress,代碼行數:59,代碼來源:versioning.ts

示例9: default

export default () => {
  const apiRoutes: Router = Router();

  const {
    MJ_APIKEY_PUBLIC,
    MJ_APIKEY_PRIVATE,
  } = process.env;

  apiRoutes.post(
    "/api/contact",
    async (req: Request, res: Response): Promise<void> => {
      const data = getPostParams(req.body);

      const mailjetClient = (mailjet as any)
        .connect(MJ_APIKEY_PUBLIC, MJ_APIKEY_PRIVATE);
      const request = mailjetClient
        .post("send", {
          version: "v3.1",
        })
        .request({
          Messages: [{
            From: {
              Email: data.email,
              Name: data.name,
            },
            To: [{
              Email: EMAIL,
              Name: RECPIENT,
            }],
            Subject: `[drublic.de] Anfrage von ${data.name}`,
            TextPart: `
Name: ${data.name}
Email-Address: ${data.name}
Message: ${data.message}${data.website ? `\n\nWebsite: ${data.website}` : ""}
            `,
          }],
        });

      try {
        const response = await new Promise((resolve, reject) => {
          request
            .then((result: any) => resolve({ success: true }))
            .catch((err: any) => reject(err));
        });
        return res.json(response).end();

      } catch (error) {
        console.error(process.env);
        console.error(error, error.trace);

        return res.json({ success: false }).end();
      }

    },
  );

  return apiRoutes;
};
開發者ID:drublic,項目名稱:vc,代碼行數:58,代碼來源:api.ts

示例10: function

export default function (): Router {

    var router: Router = Router();

    var authenticate = (req: Request, res: Response, next: any) => {
        if (!req.session["user_id"]) {
            DKYSession.raiseMessage(req.session, "danger", "You are not logged in.");
            res.redirect("/login");
        } else {
            next();
        }
    }

    // Routes.
    router.all(["/", "/label/:label?", "/p/:p?", "/label/:label?/p/:p?"], (req: Request, res: Response, next: any) => {
        defaultRoutes.index(req, res).catch(next);
    });
    router.get("/login", (req: Request, res: Response, next: any) => {
        defaultRoutes.getLogin(req, res).catch(next);
    });
    router.post("/login", (req: Request, res: Response, next: any) => {
        defaultRoutes.login(req, res).catch(next);
    });
    router.get("/logout", authenticate, (req: Request, res: Response, next: any) => {
        defaultRoutes.getLogout(req, res).catch(next);
    });
    router.post("/logout", authenticate, (req: Request, res: Response, next: any) => {
        defaultRoutes.logout(req, res).catch(next);
    });
    router.all("/post/view/:id?", (req: Request, res: Response, next: any) => {
        postRoutes.view(req, res).catch(next);
    });
    router.all("/post/:action?/:id?", authenticate, (req: Request, res: Response, next: any) => {
        postRoutes.post(req, res).catch(next);
    });
    router.all("/:alias", (req: Request, res: Response, next: any) => {
        postRoutes.view(req, res).catch(next);
    });
    // Catch all.
    router.all("*", (req: Request, res: Response, next: any) => {
        defaultRoutes.error404(req, res).catch(next);
    });

    return router;
}
開發者ID:nicholas-robson,項目名稱:dkydev_webapp,代碼行數:45,代碼來源:router.ts


注:本文中的express.Router.post方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。