尝试使用Angular2服务搜索Mlabs但找不到URL路由

时间:2018-03-05 15:21:01

标签: angular mean-stack mlab

我已经让我的本地mongodb与expressjs一起工作了,但我也想将MLABS连接到我的应用程序。我设置以下内容与MLAB交互:

const cors = require('cors');
const MLABS = require('mongoose').Mongoose;
const MONGO_URL = 'MY MONGO MLABS HERE';
var global = new MLABS();

这里我连接到MLABS,这很好用:

global.connect(MONGO_URL, function(err){
    if(err){
        console.error("Error! " + err);
    }else{
        console.log("Connected to online server");
    }
});

现在我在下面设置了以下网址来搜索mongo中的一个集合 //从数据库中搜索用户

global.get('/globalusers/:username', function(req, res, next) {
    console.log("gothere!!!");
    var username = req.params.username;
    console.log(username);
    Profile.find({username: username}, function (err, messages) {
        console.log(messages);
        if (err) {
            console.log(err);
            return res.status(500).json({
                message: 'Error while fetching data!'
            });
        }
        res.status(200).json({
            data: messages
        });    
    });
});

我在anuglar2中设置了以下服务,该服务旨在从MLABS联系上面的路线到GET json:

searchUsers(user: string) {
        return this.http.get('http://localhost:3000/globalusers/' + user )
            .map( (data: Response) => {
                const extracted = data.json();
                const msgArray: Profile[] = [];
                let message;
                for (let element of extracted.data) {
                    console.log(element.firstName);
                    message = new Profile(element.username, element.aboutMe, element.avatar, element.statusCount ,element.friendCount,element.isOnline,element.bitcoinAddress,element.email,element.lat,element.long);
                    msgArray.push(message);
                }
                return msgArray;
            });
    }

这是问题,我得到404错误状态,说我打电话时这条路线不存在,即使我认为双重检查它们是否相同?

使用expressjs路由器使用Mongoose实例触发GET到MLAB:

// Getting crypto profile from db
router.get('/globalusers/:username', function(req, res, next) {
    console.log("gothere!!!");
    var username = req.params.username;
    console.log(username);
    // Getting searched user from database
    global.get('/globalusers/' + username, function(req, res, next) {
        console.log(username);
        console.log(this.username);
        Profile.find({username: username}, function (err, messages) {
            console.log(messages);
            if (err) {
                console.log(err);
                return res.status(500).json({
                    message: 'Error while fetching data!'
                });
            }
            res.status(200).json({
                data: messages
            });    
        });
    });
});

0 个答案:

没有答案