Miha Šušteršič
Miha Šušteršič

Reputation: 10062

NodeJS express - Cannot GET route

I am creating a basic API using express and mongoose. Now I want 2 GET URLS - one for getting all the entries from the database and another for getting a random entry. Now the route defined first - '/API/getWords' works fine, but when I navigate my browser to the second route - 'API/getRandomWord' I get the following error:

Cannot GET /API/getRandomWord

Now I can't figure out what I'm doing wrong. Can I only define one app.get, and now need to define the parameters that define different functions? Or is this the 'correct' way to do it?

Thanks for the help.

My api.js:

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Words = require('./models/words.js');
//initialize our express app
var app = express();
//use body parser with JSON
app.use(bodyParser.json());

//middleware for CORS requests
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    next();
});

//addWords endpoint
app.post('/API/addWords', function(req, res) {
    //get user from request body
    var words = req.body;

    var newWords = new Words({
        quote: words.quote,
        source: words.source,
        author: words.author
    });

    newWords.save(function(err) {
        if (err) {
            if (err.code == 11000) {
                res.status(400).send({
                    message: 'This quote already exists!'
                });
            } else {
                res.status(500).send({
                    message: err.errmsg
                });
            }
        } else {
            console.log('quote saved!');
            //if all goes well, send 200 + validation message
            res.status(200).send({
                message: 'Successfully quoted!'
            });
        }
    });
});

//get all the words
app.get('/API/getWords', function(req, res) {
    Words.find({}, function(err, words) {
        if (err) {
            res.status(500).send({
                message: err.errmsg
            });
        } else {
            res.status(200).send(words);
        }
    });
});

//get a random word
app.get('API/getRandomWord', function(req, res) {
    //count ann the entries
    Words.count().exec(function(err, count) {
        //get a random number that is less or equal number of entries
        var random = Math.floor(Math.random() * count);
        //skip the random number, then return 1 entry
        Words.findOne().skip(random).exec(
            function(err, words) {
                if (err) {
                    res.status(500).send({
                        message: err.errmsg
                    });
                } else {
                    res.status(200).send(words);
                }
            });
    });
});

//connect to mongoDB
mongoose.connect('');

//define our server
var server = app.listen(3000, function() {
    console.log('api listening on ', server.address().port);
});

my model (words.js):

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var wordsSchema = new Schema({
  author: {
    type: String,
    default: 'unknown',
    index: true
  },
  source: {
    type: String,
    default: 'unknown',
    index: true
  },
  quote: {
    type: String,
    unique: true,
    required: true
  },
  created: Date,
  updated: Date
});

//create the date
wordsSchema.pre('save', function(next) {
  //get current date
  var currentDate = new Date();
  //assign date
  this.updated = currentDate;
  if (!this.created) {
    this.created = currentDate;
  }

  next();
});

var Words = mongoose.model('Words', wordsSchema);

// make this available to our users in our Node applications
module.exports = Words;

Upvotes: 1

Views: 6805

Answers (1)

mscdex
mscdex

Reputation: 106746

Your route for /API/getRandomWord is missing the leading /, so it needs to be:

app.get('/API/getRandomWord', function(req, res) {

instead of:

app.get('API/getRandomWord', function(req, res) {

Upvotes: 11

Related Questions