【问题标题】:Setting up express routing, API call returns 404 not found设置快速路由,API调用返回404 not found
【发布时间】:2016-07-22 17:46:44
【问题描述】:

我很难理解如何使用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');
    }
};

【问题讨论】:

  • app.use()router.get() 的路径将被合并 ('/game' + '/game/waiting')。所以,你已经定义了路由GET /game/game/waiting
  • 嘿,成功了。如果您发布答案,我可以接受

标签: javascript api express routing


【解决方案1】:

根据您的代码,您编写了两次“/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');
    }
};

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多