NodeJS express - 无法获取GET路由

时间:2016-03-14 19:27:28

标签: javascript node.js express

我正在使用express和mongoose创建一个基本API。现在我想要2 GET URLS - 一个用于获取数据库中的所有条目,另一个用于获取随机条目。现在首先定义的路由 - '/API/getWords'工作正常,但是当我将浏览器导航到第二条路线时'API/getRandomWord'我收到以下错误:

  

无法GET / API / getRandomWord

现在我无法弄清楚我做错了什么。我是否只能定义一个app.get,现在需要定义定义不同功能的参数?或者这是“正确”的方式吗?

感谢您的帮助。

我的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);
});

我的模特(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;

1 个答案:

答案 0 :(得分:8)

use warnings; use strict; use Test::More; use constant { ERROR_AED => { errorCode => 561, message => "this is an error.\n", tt => { template => 'disabled'}, link => 'www.error-fix.com', }, }; my $error = ERROR_AED; is (ref $error, 'HASH', 'ERROR_AED is a hashref'); is (defined $error->{errorCode}, 1, 'ERROR_AED contains an errorCode key'); is ($error->{errorCode}, 561, 'ERROR_AED errorCode is correct'); is (defined $error->{message}, 1, 'ERROR_AED contains key message'); like ($error->{message}, qr/this is an error/, 'ERROR_AED msg output is ok'); is (defined $error->{tt}, 1, 'ERROR_AED contains key tt'); is (ref $error->{tt}, 'HASH', 'ERROR_AED tt is a hashref'); is (defined $error->{tt}{template}, 1, 'ERROR_AED tt href contains template key'); is ($error->{tt}{template}, 'disabled', 'ERROR_AED tt template is ok'); is (defined $error->{link}, 1, 'ERROR_AED has a link key'); is ($error->{link}, 'www.error-fix.com', 'ERROR_AED link is ok'); done_testing(); 的路线缺少前导/API/getRandomWord,因此需要:

/

而不是:

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