设置快速路由,API调用返回404未找到

时间:2016-04-03 03:48:22

标签: javascript api express routing

我很难理解如何使用app.userouter来设置我的快速路由。我从文档中了解到的方法是,您可以设置路由器,然后将其传递到app.use()的路由,并让该路由器处理到该路由的所有路由。有人可以帮我理解我的逻辑是什么吗?任何帮助非常感谢。

路由

var express = require('express'),
    router = express.Router(),
    mongoose = require('mongoose'),
    PlayingGame = mongoose.model('PlayingGame'),
    FinishedGame = mongoose.model('FinishedGame');


var waiting_user = null;

module.exports = function(app) {
    app.use('/game', router);
};

router.get('/game/waiting', function(req, res, next) {
    if (waiting_user !== null) {
        console.log('lets put you two in game');
    } else {
        console.log('you need to wait for another player');
    }
});

客户来电

var play = () => {
    var username = username_input.val();

    if (isUsernameValid(username)) {
        $.ajax({
                url: '/game/waiting',
                type: 'GET',
            })
            .done(function() {
                console.log("success");
            })
            .fail(function() {
                console.log("error");
            })
            .always(function() {
                console.log("complete");
            });
    } else {
        alert('Put in a valid username');
    }
};

1 个答案:

答案 0 :(得分:0)

根据你的代码,你写了两次“/game”,这意味着你的路线变成了“baseurl:3000/game/game/waiting”。

如果您不想更改路线,请更新:

// remove this : router.get('/game/waiting', function(req, res, next) {
router.get('/waiting', function(req, res, next) {
    if (waiting_user !== null) {
        console.log('lets put you two in game');
    } else {
        console.log('you need to wait for another player');
    }
})

但是如果您想在客户端调用时进行更改,您可以更新:

var play = () => {
    var username = username_input.val();

    if (isUsernameValid(username)) {
        $.ajax({
                url: '/game/game/waiting',  /* remove this : '/game/waiting', */
                type: 'GET',
            })
            .done(function() {
                console.log("success");
            })
            .fail(function() {
                console.log("error");
            })
            .always(function() {
                console.log("complete");
            });
    } else {
        alert('Put in a valid username');
    }
};