5

I'm trying to use express in a prototype

function ioServer() {

}

module.exports = ioServer;

ioServer.prototype.start = function() {
    var app       = require('express')
    var http      = require('http').Server(app)
    var io        = require('socket.io')(http)

    app.get('/', function(req, res) {
        var outPut = ""
        res.sendFile(__dirname + './client/index.html')
    })

    http.listen(3000, function(port) {
        console.log('Listening on port, ' + 3000)
    })
}

But when I use it It throws the error TypeError: app.get is not a function When I remove the prototype part it works.

  • When you use `require('express')()`, you are calling that function immediately and it returns an express application instance. This is the object that you use to configure your application and set up routes. So, the difference between `const express = require('express')` and `const express = require('express')()` is that the first one just imports the express module, while the second one imports it and creates an instance of the express application. – Drew Pesall Jan 16 '23 at 02:22

2 Answers2

31

Your app should be an instance of express.

For example, you could include it like this:

var app = require('express')();
svens
  • 11,438
  • 6
  • 36
  • 55
4

when you require express you forgot to place ( ) try this

const app = require('express')();
Muhammad Awais
  • 156
  • 1
  • 6