learningcoding
learningcoding

Reputation: 197

Node express server isn't working - how to create and start a server?

I am trying to create and start a server and I've been looking at other code and can't see why mine isn't working (just getting this: localhost just keeps loading and loading and nothing happens). Any ideas? Thanks!!!

app/server/app.js :

'use strict'

var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');

var app= express();
module.exports = app;

app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


var server = http.createServer();
  server.listen(1337, function () {
        console.log('Server is listening on port 1337!');
  });

app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);

});

app/browser/index.html :

<!DOCTYPE html>
<html lang="en">
 <head>
   <title>node</title>   
 </head>
 <body>
    <div>
     <p>Hey whats up</p>
    </div>
  </body>
</html>

Upvotes: 1

Views: 3906

Answers (2)

mfkogan
mfkogan

Reputation: 60

Your code works for me.

The only thing wrong in your code is you have to change server.listen(1337, function ()..., to app.listen(1337, function () {...

Also, I added a file path...

app.get('/', function(req, res){ res.sendFile(path.join(__dirname, '/index.html'));})

...to link your localhost:1337 to your index.html file. Now your index.html file will display when you go to localhost:1337.

Lastly, I'm not sure if you need this line... var server = http.createServer();. I deleted it and everything worked fine.

Here's the code below.

'use strict'

var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');

var app= express();
module.exports = app;

app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/', function(req, res){
	res.sendFile(path.join(__dirname, '/index.html'));
})

  app.listen(1337, function () {
        console.log('Server is listening on port 1337!');
  });

app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);

});

Upvotes: 2

rafal_zonk
rafal_zonk

Reputation: 76

Maybe the port You wrote - 1337 is busy, check by choosing other port, for example 4200, or 3000 - server.listen(4200,function () {

Upvotes: 0

Related Questions