简体   繁体   中英

Some of my routes don't work in express

I'm trying to create a tic-tac-toe game and want to save the user data into a database, but my problem is that the router I want to do this with can't be reached, I get an 'Internal server error message(500)'.

Here is the 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;

Here is the 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();
    }
}

My problem is with

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

and the

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

works just fine, it inserts the sent data into database.

Any help would be appreciated!

Seems that you forgot to import the mongodb bindings for express.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM