Why is createServer () not considered a function?

I installed express globally and npm, installed my express application, but neither the skill nor the application work (I use the visual studio code on Mac OS Yosemite).

Here is a sample code:

/// <reference path="typings/node/node.d.ts" /> /// <reference path="typings/express/express.d.ts" /> var express = require('express'); var app = express.createServer(); app.get('/', function (req, res) { res.send('hi'); }) app.listen(8000); 

and here are the errors that I get:

 Abeds-MacBook-Pro:myNode AZ$ node twitter.js /Users/AZ/Desktop/myNode/twitter.js:5 var app = express.createServer(); ^ TypeError: express.createServer is not a function at Object.<anonymous> (/Users/AZ/Desktop/myNode/twitter.js:5:19) at Module._compile (module.js:397:26) at Object.Module._extensions..js (module.js:404:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:429:10) at startup (node.js:139:18) at node.js:999:3 

I did a little research and found that createServer () is deprecated. I read that I need to change the version somewhere in my application.

Here is the folder of my application

Note. I made another application using purely Node.js, and createServer () worked without any error along with intellisence.

EDIT: in another application, I used require('net') .

I changed my code to the following:

 var express = require('express') , http = require('http'); var app = express(); var server = http.createServer(app); console.log('Listening on port 8000') app.get('/', function (req, res) { res.send('hi'); }) app.listen(8000) 

Now the problem is that res.send('hi'); was not reached, otherwise I can not send to the client.

EDIT 2:

I tried the following code in one of the answers:

 const express = require('express'); const http = require('http'); const app = express(); const server = http.createServer(app).listen(8080, function(err) { if (err) { console.log(err); } else { const host = server.address().address; const port = server.address().port; console.log(`Server listening on ${host}:${port}`); } }); app.get('/', function (req, res) { res.send('hi'); }) 

res.send('hi'); still not working and it is not reporting an error.

+5
source share
1 answer

createServer is a function of http , so it should be:

 const express = require('express'); const http = require('http'); const app = express(); app.get('/', function (req, res) { res.send('hi'); }); const server = http.createServer(app).listen(8080, function(err) { if (err) { console.log(err); } else { const host = server.address().address; const port = server.address().port; console.log(`Server listening on ${host}:${port}`); } }); 

PS Installing express everywhere is a bad idea.

+5
source

Source: https://habr.com/ru/post/1240763/


All Articles