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


TypeScript express.Router類代碼示例

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


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

示例1: Logger

import * as express from "express";
import {NextFunction, Request, Response, Router} from "express";
import * as path from "path";
import {GraphQLRouter} from "@GraphQL/index";
import {Logger} from "@utils";
import config from "@config";

const logs = Logger(module);
const router: Router = express.Router();

function error404(req: Request, res: Response, next: NextFunction): void {
    logs.debug("Not found URL: %s", req.url);
    const err: any = new Error("Not found");
    err.status = 404;
    next(err);
}

function onError(err: any, req: Request, res: Response): void {
    logs.error("Internal error(%d): %s", res.statusCode, err.message);
    res.locals.message = err.message;
    res.locals.error = config.get("isDev") ? err : {};
    res.status(err.status || 500);
    res.json({
        message: err.message || "Server error",
    });
}

function onSPA(req: Request, res: Response): void {
    logs.info(path.join(__dirname,"../public/index.html"));
    res.sendFile(path.join(__dirname, "../public/index.html"));
}
開發者ID:ZulusK,項目名稱:Budgetarium,代碼行數:31,代碼來源:index.ts

示例2: require

import { Router } from 'express';
var authenticatedPolicy = require("../../policies/authenticated");
import { CollaboratorController } from "../../../app/controllers/collaborator/collaborator.controller";

export const COLLABORATOR_MAIN_ROUTER: Router = Router();
// define routes
//create
COLLABORATOR_MAIN_ROUTER.post('/', CollaboratorController.create);
//getById
COLLABORATOR_MAIN_ROUTER.get('/:id', authenticatedPolicy, CollaboratorController.getById);
//getAll
COLLABORATOR_MAIN_ROUTER.post('/getAll', CollaboratorController.getAll);
//update
COLLABORATOR_MAIN_ROUTER.put('/:id', authenticatedPolicy, CollaboratorController.updateById);

//delete
COLLABORATOR_MAIN_ROUTER.delete('/:id', authenticatedPolicy, CollaboratorController.deleteById);

開發者ID:twicepixels,項目名稱:tp-main-api,代碼行數:17,代碼來源:collaborator.route.ts

示例3: Router

import {Router} from 'express';

const index: Router = Router();

index.get('/', (req, res, next) => {
   res.send('foobar'); 
});

export default index;
開發者ID:todd,項目名稱:express_ts,代碼行數:9,代碼來源:index.ts

示例4: Router

"use strict";

import { Router } from "express";

import { Passport } from "../server";
import * as userApi from "../controllers/user";

const router: Router = Router();
const frontEndOriginUrl = process.env.FRONTEND_URL;
const frontEndInitializeUrl = `${frontEndOriginUrl}/initialize`;


/**
 * @api {get} /google
 * @description Passport Google Authentication - Holds the redirection from your app to gmail login page.
 */
router.get("/google", Passport.authenticate("google", { scope: [ "profile", "email" ] }));


/**
 * @api {get} /google/callback
 * @description Handles the callback after google has authenticated the user.
 *
 * * @successRedirect 1 is enum value for Facebook. Facebook ang Google both uses localhost except for twitter 127.0.0.1.
 * This will be filtered out on Front End and set the base url as either localhost or 127.0.0.1 base on the enum id used.
 */
router.get("/google/callback", Passport.authenticate("google", {
  successRedirect: `${frontEndInitializeUrl}/1`,
  failureRedirect: "/"
}));
開發者ID:KShewengerz,項目名稱:ngx-express-passport-setup,代碼行數:30,代碼來源:auth.ts

示例5: Router

import { Router, Request, Response } from "express";

const usersRouter: Router = Router();

usersRouter.get("/", function (req: Request, res: Response, next: any) {
    res.send("respond with a resource");
});

export {usersRouter}
開發者ID:thorti1985,項目名稱:pl_mean,代碼行數:9,代碼來源:users.ts

示例6: Router

import { Router, Response, Request } from 'express';

export const studyEntityRouter: Router = Router();

studyEntityRouter.get('/', (request: Request, response: Response) => {
  response.json([  {id: 1, name: 'Qrwerewrwe', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 2, name: 'Nererew', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 3, name: 'Boewrewr', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 4, name: 'Celeritas', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 5, name: 'Magneta', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 6, name: 'RubberMan', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 7, name: 'Dynama', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 8, name: 'Dewrew', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 9, name: 'Magma', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}},
  {id: 10, name: 'Tornado', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}}
  ]);
});

studyEntityRouter.get('/:id', (request: Request, response: Response) => {
  response.json(
      {id: 3, name: 'Boewrewr', content: {html: '<h1>asdfsdf</h2><p>asdfasdfasdfasdf</p>'}}
  );
});
開發者ID:akazimirov,項目名稱:domic,代碼行數:23,代碼來源:study_entity.ts

示例7: create

    public static create(router: Router) {
        // log
        console.log("[IndexRoute::create] Creating index route.");

        // add home page route
        router.get("/", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().index(req, res, next);
        });

        // we will post to the root if we have a login fail
        router.post("/", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().index(req, res, next);
        });

        // router.post("/login", (req: Request, res: Response, next: NextFunction) => {
        //     new IndexRoute().login(req, res, next);
        // });
        
        //add admin page to import reactions and get depictions
        router.post("/admin", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().admin(req, res, next);
        });

        //if accessed through GET request or directly by URL
        router.get("/admin", (req: Request, res: Response, next: NextFunction) => {
            res.send("You either do not have permission to access this page, or you are trying to access it directly.  If you are an admin, please authenticate and try again.")
        })

        // handles ajax request to get depictions
        router.post("/getImage", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().getImage(req, res, next);
        });
        
        //add game page route POST --> in class mode with leaderboard after user authentication
        router.post("/game", (req: Request, res: Response, next: NextFunction) => {
            //new IndexRoute().game(req, res, next);
            new IndexRoute().login(req, res, next);
        });

        //GET --> practice mode, no leaderboard effect
        router.get("/game", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().game(req, res, next);
        });

        //insert reaction and cards to db
	    router.post("/addReaction", (req: Request, res: Response, next: NextFunction) => {
	        new IndexRoute().addReaction(req, res, next);
	    });
    
        //return 'deck' of cards from db for game use
	    router.post("/generateCards", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().generateCards(req, res, next);
        });

        //return set of all reactions in db for solution checking
        router.post("/generateSolutions", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().generateSolutions(req, res, next);
        });

        //export current reactions from db to csv file for download
        router.get("/exportReactions", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().exportReactions(req, res, next);
        });

        //export users and points from db to csv file for download
        router.get("/exportPoints", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().exportPoints(req, res, next);
        });

        //reset all user points to 0
        router.get("/resetPoints", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().resetPoints(req, res, next);
        });

        router.get("/getLeaderboard", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().getLeaderboard(req, res, next);
        });

        router.post("/updateLeaderboard", (req: Request, res: Response, next: NextFunction) => {
            new IndexRoute().updateLeaderboard(req, res, next);
        })

    }
開發者ID:TeddyRandby,項目名稱:ChemistryAgainstHumanity,代碼行數:83,代碼來源:index.ts

示例8: Router

import { Router } from "express";
import { COLLABORATOR_MAIN_ROUTER } from "./collaborator.route";
import { IMAGE_ROUTER } from "./image.route";

let router: Router = Router();
router.use("/", COLLABORATOR_MAIN_ROUTER);
router.use("/image", IMAGE_ROUTER);

export const COLLABORATOR_ROUTER: Router = router;
開發者ID:twicepixels,項目名稱:tp-main-api,代碼行數:9,代碼來源:router.ts

示例9: require

import {Router, Request, Response } from 'express';
import db from "../../db";
import fs = require("fs");
import path = require("path");
import config from "../../config";
const SAVE_DIR = config.settings.saveDir;

const router: Router = Router();

// GET tracks listing.
router.get('/', (req: Request, res: Response) => {
  db.Track.findAll({ raw: true })
  .then(tracks => res.send(tracks));
});

// Get track info.
router.get('/:trackId', (req: Request, res: Response) => {
  const trackId = req.params.trackId;
  db.Track.findById(trackId)
  .then(track => res.send(track));
});

// Get todo info.
router.get('/:trackId/config', (req: Request, res: Response) => {
  const trackId = req.params.trackId;
  db.Track.findById(trackId)
  .then((track) => {
    if(track) {
      const configFilePath = path.join(SAVE_DIR, track.name, "config.json");
      fs.readFile(configFilePath, 'utf8', function(err, data) {
        if (err) {
開發者ID:StaceC,項目名稱:implib,代碼行數:31,代碼來源:tracks.ts

示例10: Router

import { Router, Response } from "express";
import { verify } from "jsonwebtoken";
import { secret } from "../config";

const protectedRouter: Router = Router();

protectedRouter.use(function(req: any, res: Response, next) {
    const token = req.headers.auth;
    console.log(token);
    verify(token, secret, function(tokenError) {
        if (tokenError) {
            return res.status(500).json({
                message: "Invalid token, please Log in first"
            });
        }

        next();
    });
});

protectedRouter.get("/", function(req, res) {
    res.json({
        text: "Greetings, you have valid token.",
        title: "Protected call"
    });
});

export {protectedRouter}


開發者ID:BLamy,項目名稱:angular2-express-starter,代碼行數:28,代碼來源:protected.ts

示例11: require

import { Router, Request, Response, NextFunction } from "express";

import User = require('../models/user');

const userRouter: Router = Router();


userRouter.get('/', function (req: Request, res: Response, next: NextFunction) {
    console.log('got "/" route');
    // let user = new User({
    //     firstName: 'Alex',
    //     lastName: 'Borisov',
    //     password: 'pass',
    //     email: 'email@mail.mail'
    // });
    // user.save();
    res.redirect('/');

});

export {userRouter}
開發者ID:Chicloon,項目名稱:conf,代碼行數:21,代碼來源:user.ts

示例12: Router

import {Router} from 'express';
import {Response} from 'express';
import * as jwt from 'jsonwebtoken';
import {Authentication} from '../authentication';
import {IRequest} from '../interfaces';
import {secretTokenKey} from '../config';
import {IUser, User} from '../models/user';
import {NextFunction} from 'express';

namespace AuthenticateRouter {
  'use strict';

  export const router: Router = Router();

  router.get('/', function (req: IRequest, res: Response): void {
    Authentication.checkAuthentication(req, function (isAuth: boolean): void {
      if (isAuth === false) {
        res.json({
          message: 'you are not authenticated',
          success: false
        });
      } else {
        res.json({success: true});
      }
    });
  });

  router.post('/', function (req: IRequest, res: Response, next: NextFunction): void {
    req.checkBody('identifier', 'required').notEmpty();
    req.checkBody('password', 'required').notEmpty();
    let errors: Object = req.validationErrors();
開發者ID:dadakoko,項目名稱:play-server,代碼行數:31,代碼來源:authenticate.ts

示例13: route

 public route(router: Router): void {
     router.get('/', this.sayHi.bind(this));
     router.get('/log', this.showLog.bind(this));
     router.get('/dbTest', this.dbProcess.bind(this));
     router.get('/health', this.dbProcess.bind(this));
 }
開發者ID:VestaRayanAfzar,項目名稱:express-api-template,代碼行數:6,代碼來源:IndexController.ts

示例14: Router

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* tslint:disable:max-line-length */
import {Router} from 'express';

// Einlesen von application/json im Request-Rumpf
// Fuer multimediale Daten (Videos, Bilder, Audios): raw-body
import {json} from 'body-parser';

import {getById, getByQuery, post, put, deleteFn} from './videos_request_handler';
import {validateJwt, isAdmin, isAdminMitarbeiter} from '../../iam/router/iam_request_handler';
import {validateMongoId} from '../../shared/shared';
/* tslint:enable:max-line-length */

// http://expressjs.com/en/api.html
// Ein Router ist eine "Mini-Anwendung" mit Express
const buecherRouter: Router = Router();
buecherRouter.route('/')
    .get(getByQuery)
    .post(validateJwt, isAdminMitarbeiter, json(), post)
    .put(validateJwt, isAdminMitarbeiter, json(), put);

const idParam: string = 'id';
buecherRouter.param(idParam, validateMongoId)
    .get(`/:${idParam}`, getById)
    .delete(`/:${idParam}`, validateJwt, isAdmin, deleteFn);

export default buecherRouter;
開發者ID:AdrianFoell,項目名稱:VP,代碼行數:30,代碼來源:index.ts

示例15: Router

import { Router, Response, Request } from 'express';

const publicRouter: Router = Router();

publicRouter.get('/simple', (request: Request, response: Response) => {
  response.json({
    title: 'Greetings.',
    text: 'Hello Angular 2'
  });
});

export { publicRouter }
開發者ID:akazimirov,項目名稱:domic,代碼行數:12,代碼來源:public.ts


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