Search code examples
javascriptnode.jsexpresstypescripthttpserver

Using TypeScript and Express, views do not render. Instead server files are shown


I'm trying to create a webapp using TypeScript. I have my app.js file creating a server, but the route I'm defining is never hit. Instead, files on the server at the root of the project are shown.

Here is my code.

//app.ts
import * as express from 'express';
import * as http from 'http-server';

let app = express();

app.set('port', 443);
app.set('views', './views');
app.set('view engine', 'jade');

app.get('/', function(req: any, res: any) {
    // This code is never reached on 'GET /' requests.
    res.render('index');
});

app.use(function(req: any, res: any, next: any) {});
app.use(function(err, req, res, next) {});

http.createServer().listen(app.get('port'));

console.log("Listening...");

When I go to localhost:443 I'm met with the image below.

showing server files instead of rendering

In messing around with the code I'm able to do an app.render() call to see the rendered HTML as a string in the debugger, which is more than I can get out of this configuration, but even still just calling app.render('index'); doesn't actually render anything. Sample below.

app.render('index', function(err: Error, html: string) {
    console.log(html); // Outputs the rendered view, but it is not rendered on the page.
});

What do you think?


Solution

  • You haven't used your express instance as server.

    You need to do this

    http.createServer(app).listen(app.get('port'));
    

    Or

    app.listen(app.get('port'))
    

    Basically you called your server without any handler, so it shows your directory of main script.

    You have created express instance, but did not added to http server.