Ryan
Ryan

Reputation: 29

node.js express generator app not responding

The only file/folder ive changed is the main app.js after i installed express generator and npm install. Im a newb, maybe its its a typo in the app.js file. Heres the file and console output. Thanks so much. when i go to localhost:3000 on chrome it says cannot GET/ and it failed to load resource in console 404 and on the comm line it says GET / 404 11.960 ms - 13 everytime i reload the page

^Cryan@\Ryan:~/Desktop/node/frameworks/expressapi$ npm start

> [email protected] start /home/ryan/Desktop/node/frameworks/expressapi
> node ./bin/www

curl -X get http://localhost:3000/products

curl -X DELETE http://localhost:3000/products/2

and the app.js file

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes');
var users = require('./routes/users');

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var products = [
    {
      id: 0,
      name: 'watch',
      description: 'tell time with this amazing watch',
      price: 30.00
    },
    {
      id: 1,
      name: 'sandals',
      description: 'walk in comfort with these sansdals',
      price: 10.00
    },
    {
      id: 2,
      name: 'watch',
      description: 'protect your eyes!',
      price: 25.00
    }
];

app.get('./routes');

app.get('/products', function(req, res) {
  res.json(products);
});

app.get('/products/:id', function(req, res) {
  if (req.params.id > (products.length - 1) || req.params.id < 0) {
    res.statusCode = 404;
    res.end('NotFound');
  }
  res.json(products[req.params.id]);
});

app.post('/products', function(req, res) {
  if (typeof req.body.name === 'undefined') {
    res.statusCode = 400;
    res.end('a product name is required');
  }
  products.push(req.body);
  res.send(req.body);
});

app.put('/products/:id', function(req, res) {
  if (req.params.id > (products.length - 1) || req.params.id < 0) {
    res.statusCode = 404;
    res.end('not found');
  }
  products[req.params.id] = req.body;
  res.send(req.body);
});

app.delete('/products/:id', function(req, res) {
  if (req.params.id > (products.length - 1) || req.params.id < 0) {
    res.statusCode = 400;
    res.end('not found for that id');
  }
  products.splice(req.params.id, 1);
  res.json(products);
});

module.exports = app;

and here iis the www file

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('expressapi:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Upvotes: 0

Views: 893

Answers (1)

Alex da Silva
Alex da Silva

Reputation: 4590

I run your code and it looks fine. It does not have a route for "/", so you will get a Cannot GET / message in the browser if you enter http://localhost:3000/

http://localhost:3000/products returns your JSON data correctly.

For the curl command you have to use GET in capital letters:

curl -X GET http://localhost:3000/products
[{"id":0,"name":"watch","description":"tell time with this amazing watch","price":30},{"id":1,"name":"sandals","description":"walk in comfort with these sansdals","price":10},{"id":2,"name":"watch","description":"protect your eyes!","price":25}]

If you want to add the default '/' route from express generator, change your app.js file on line with this code:

var routes = require('./routes/index');

And then add the following line later on in the code:

app.use('/', routes);

You will then see the Welcome to Express message when you point your browser to http://localhost:3000

I hope that helps clarify.

Upvotes: 1

Related Questions