本文整理汇总了TypeScript中express.Router类的典型用法代码示例。如果您正苦于以下问题:TypeScript Router类的具体用法?TypeScript Router怎么用?TypeScript Router使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Router类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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 protected]'
// });
// 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
示例16: Router
import {Request, Response, Router} from "express";
const router: Router = Router();
import {IRoute} from "express-serve-static-core";
import {objectModel} from "../models/models";
import {checkObjectIDValidity, checkIfDataIsArray} from "../helpers/validation";
import {errorIDValidationMessages, errorApiMessages} from "../helpers/errorMessages";
const api: IRoute = router.route("/api/object/:id");
api.get(async (req: Request, res: Response) => {
let id: string = req.params.id;
if (!checkObjectIDValidity(id)) {
res.status(400).json(errorIDValidationMessages.getMessage);
}
let obj: Object = await objectModel
.find({_id: id})
.exec();
res.json(obj);
});
api.post(async (req: Request, res: Response) => {
// check data before saving also could do validation within function
let obj: Array<Object> = checkIfDataIsArray(req.body);
let dataRes: Object = await objectModel.insertMany(obj);
res.status(200).json(dataRes);
});
api.put(async (req: Request, res: Response) => {
开发者ID:vildantursic,项目名称:walter,代码行数:31,代码来源:object.ts
示例17: constructor
constructor() {
this.router = Router()
// Parse incoming requests with JSON payloads http://expressjs.com/en/api.html
this.router.use(express.json({ limit: '50mb' }))
}
开发者ID:OurWorldInData,项目名称:owid-grapher,代码行数:5,代码来源:api.ts
示例18: constructor
constructor(router: Router) {
router.route('/user/authorize').get(this.authorize);
router.route('/user/login').post(this.login.bind(this));
router.route('/user/current').get(this.current);
router.route('/user/can').get(this.can);
}
开发者ID:apache,项目名称:helix,代码行数:6,代码来源:user.ts
示例19: renderError
const getPageController = (page: PageInterface): void => {
indexRoutes.get(
page.action,
async (req: Request, res: Response): Promise<void> => {
const templateData: TemplateDataInterface = getTemplateData(page);
if (!page.content) {
return renderError(res, templateData);
}
// Blog Page render
if (page.action.startsWith("/blog")) {
const slug: string = req.params.id;
const post = page.action !== "/blog"
? await getPost(posts, slug)
: null;
if (post) {
if (post.error) {
return renderError(res, templateData);
}
if (post.redirect) {
return res.status(301)
.redirect(`https://archive.drublic.de/blog/${post.redirect}`);
}
}
return res.render(page.content, {
...templateData,
...getPostsData(),
post,
});
}
if (page.action === "/") {
const data = {
...templateData,
...getPostsData(),
...getWdPostsData(),
};
return res
.set({
"Cache-Control": `max-age=${60 * 60 * 24}`,
})
.render(page.content, data);
}
// Normal page render
try {
return res
.set({
"Cache-Control": `max-age=${60 * 60 * 24}`,
})
.render(page.content, templateData);
} catch (error) {
return renderError(res, templateData);
}
},
);
};
开发者ID:drublic,项目名称:vc,代码行数:62,代码来源:index.ts
注:本文中的express.Router类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论