簡體   English   中英

我的某些路線不適用於快遞

[英]Some of my routes don't work in express

我正在嘗試創建一個井字游戲,想將用戶數據保存到數據庫中,但是我的問題是我要使用的路由器無法連接,我收到“內部服務器錯誤message(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() {...});

工作正常,它將發送的數據插入數據庫。

任何幫助,將不勝感激!

似乎您忘記導入mongodb綁定以進行表達。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM