Bill Pope
Bill Pope

Reputation: 591

simple node server returning "Cannot GET/"

I have this simple server and when I go to localhost:3000 I get "Cannot GET /" I t fails when I try and call /register as well. Any ideas? thanks

var express = require('express');
var gcm = require('node-gcm');
var apn = require('apn');

var app = express();
var device_token;

 /*
 , function(){
 var host = server.address().address;
 var port = server.address().port;
 console.log(port, host);
 }
*/
 app.listen(3000);

 app.use(function(req, res, next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,    Content-Type, Accept");
   next();
 });

app.post('/register', function(req, res){
   device_token = req.body.device_token;
   console.log('device token received');
   console.log(device_token);

   res.send('ok');
});

Upvotes: 1

Views: 940

Answers (2)

morganbaz
morganbaz

Reputation: 3117

You have no defined route for /. /register does not work because you have app.post, which only accepts POST requests. If you want the GET request to /register to work, add this piece of code:

app.get('/register', function(req, res) {
    res.send("It works!");
});

Upvotes: 1

agconti
agconti

Reputation: 18123

Navigating to a page in your browser is a GET request. You've only defined a handler for a POST request for the route /register:

app.post('/register', function(req, res){
   device_token = req.body.device_token;
   console.log('device token received');
   console.log(device_token);

   res.send('ok');
});

You haven't defined any thing for the / route. So when you navigate to either, it rightfully throws Cannot GET becuase either that route itself isn't defined, ie for /, or the GET method for that route isn't defined, ie. for /register.

You can allow a GET request at the root url ( / ) with:

app.get('/', function(req, res){
  res.send('Hello!')
})

For the /register route, you should not use a GET request because you need to send information in the request body to actually register a user. ( Only post requests allow this ).

You've set it up correctly. You just can't view it in the browser. Test it out with postman or curl to see if it works.

Upvotes: 2

Related Questions