I'm trying to build an express project. After I npm install, create server.js and node server.js, I got this error:
var app = module.exports = express.createServer(); ^ TypeError: undefined is not a function at Object.<anonymous> (/Users/zez/Desktop/node/nodeblog/server.js:3:36) at Module._compile (module.js:449:26) at Object.Module._extensions..js (module.js:467:10) at Module.load (module.js:349:32) at Function.Module._load (module.js:305:12) at Function.Module.runMain (module.js:490:10) at startup (node.js:124:16) at node.js:807:3
and here is my code in server.js:
var express = require('express'); var app = module.exports = express.createServer(); app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.get('/', function(req, res){ res.render('index', { title: 'Express' }); }); app.listen(3000);
createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.
Like most Node. js functions, createServer() takes a callback function as an argument. This callback function is executed each time the server receives a new request.
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.
createServer() passes two arguments to the callback when you call it. The first is the http request object, the second is the http response object. If your callback wants to work properly and use those arguments, it must create two arguments that match those. You can name them anything you want.
Change:
var express = require('express'); var app = module.exports = express.createServer();
To:
var express = require('express'); var app = express(); //Middleware app.listen(3000)
You can also globally install express with the following command and then automatically generate a express template with the following command:
npm install -g express
Generate template:
express myAppName cd . && npm install
express.createServer() has been deprecated, perhaps your project's package.json is pointing at the latest version? Try pinning it to 2.5.10 and npm install again. Or check Nodejs / Express - Launching my app: express.createServer() is deprecated on how to update the project to work with more recent versions of express.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With