我很难理解如何使用app.use
和router
来设置我的快速路由。我从文档中了解到的方法是,您可以设置路由器,然后将其传递到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');
}
};
答案 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');
}
};