我的一些路线不在快递中工作

时间:2016-05-11 19:37:20

标签: javascript node.js express

我试图创建一个井字游戏,并希望将用户数据保存到数据库中,但我的问题是我想要做到的路由器无法到达,我收到了“内部服务器”错误消息(500)'。

这是index.js:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Lab5' });
});

//check if server is online
router.get('/alive', function(req, res, next) {
    res.send('alive');
});

router.post('/alive', function(req, res) {
    //here I generate the next step for the game
});

//this route can't be reached
router.get('/db', function(res, req) {
    var db = req.db;
    var collection = db.get('usercollection');

    collection.find({}, {}, function(e, docs) {
        res.send(JSON.stringify(docs));
    });
});

//and this route can be reached
router.post('/db', function(req, res) {
    var db = req.db;
    var collection = db.get('usercollection');

    var username = req.body.username;
    var gameStatus = req.body.gameStatus;

    try {
        if(Object.keys(req.body).length !== 0 && JSON.stringify(req.body) !== JSON.stringify({})){
            console.log("Data insert...");
            collection.insert({
                "username" : username,
                "gameStatus" : gameStatus
            }, function (err, docs) {
                if(err) {
                    res.send("Error inserting data into database!");
                }
            });
        }
    } catch(err) {
        console.log("Error in insert: " + err);
    }
});

module.exports = router;

这是getDB.js:

function getDB() {
    var xhttp = createRequest();

    if(xhttp === null) {
        alert("Ajax object not supported by your browser!");
    }
    else {
        xhttp.onreadystatechange = function() {
            if(xhttp.readyState == 4 && xhttp.status == 200) {
                if(xhttp.responseText != null) {
                    var db = JSON.parse(xhttp.responseText);

                    console.log(db);
                }
            }
        }


        xhttp.open('GET', 'db', true);
        xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhttp.send();
    }
}

我的问题在于

router.get('/db', function() {...});

router.post('/db', function() {...});

工作正常,它将发送的数据插入数据库。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

似乎您忘记为明文导入mongodb绑定。

https://www.npmjs.com/package/express-mongo-db