Tuesday, 14 March 2017

Express Typescript Router Not Working

Im trying to get this express application to run and i dont know whats wrong with my code but the router seem not to be working.

This is my app.ts

var path = require('path');
var logger = require('morgan');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
import {Request, Response, Router} from "express";

// Import our application router class to handle routing.
import {ApplicationRouter} from './routes/index';

// Module for the express application
var app = express();

// Our express middleware.
app.use( logger('dev') );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: false }) );
app.use( cookieParser() );
app.use( (req: Request, res: Response, next: Function) => {
  res.header( 'Access-Control-Allow-Origin', '*' );
  res.header( 'Access-Control-Allow-Method', 'GET, POST, PUT, PATCH, DELETE, OPTIONS' );
  res.header( 'Access-Control-Allow-Header', 'Origin, X-Requested-With, Content-Type, Accept' );
});

// Router Module
let appRouter = new ApplicationRouter();

// Application's routes.
app.use( appRouter.getIndex() );

// Catch 404 and forward to error handler.
app.use( (req: Request, res: Response, next: Function) => {
  var error: any = new Error('Not Found');
  error.status = 404;
  next( error );
});

// Development error handler will print stacktrace.
if ( app.get('env') === 'development' ) {
  app.use( (error: any, req: Request, res: Response, next: Function) => {
    return res.status( error.status || 500 );
}

// Production error handler prints no stacktrace to user.
app.use( (error: any, req: Request, res: Response, next: Function) => {
  return res.status( error.status || 500 );
});

module.exports = app;

And this is my router (index.ts)

import * as express from 'express';

export class ApplicationRouter {

  private router: express.Router;

  constructor() {
    this.router = express.Router();
  }

  getIndex() {
    return this.router.get( '/', (req: express.Request, res: express.Response, next: Function) => {
      res.json( 'Welcome to Kriddl Vote Polling System. [Beta 0.0.1 - Dev]' );
    });
  }
}

Wjat am i doing wrong ?. Am using gulp to build the project. When i run the app, it just keeps loading and loading.



via Ralph Marvin

No comments:

Post a Comment