为什么我从我server.js文件null或[]回应? [英] Why I get a null or [ ] response from my server.js file?

查看:89
本文介绍了为什么我从我server.js文件null或[]回应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做基础上的电视showTracker 以及到目前为止,我不能得到任何表演到我的网站。我一直在努力地试图是否我犯了一个错误,但我还是没能发现任何东西。因此,如何我检索这些信息。我曾经在盯着另一个CMD这server.js和mongod的单独的CMD中并一饮而尽我仍然无法得到任何的表演。当我看到的反应,它会显示一个空阵[]像这样。因此,任何建议?帮助将AP最多preciated。 (我有主办的网站还没有,认为这也将有助于我的问题)。净调试器的错误表示API /表演/ - 响应= []

下面是我的server.jsrespone

  VAR猫鼬=要求('猫鼬');
VAR bcrypt =要求('bcryptjs');
VAR前preSS =要求('前preSS');
VAR路径=要求('路径');
VAR记录=要求('摩根');
VAR cookieParser =要求('cookie的解析器');
VAR bodyParser =要求('身体分析器');
VAR会话=要求('前preSS-届');
VAR护照=要求('护照');
VAR LocalStrategy =要求('护照本地')战略。VAR showSchema =新mongoose.Schema({
    _身份证号,
    名称:字符串,
    airsDayOfWeek:字符串,
    airsTime:字符串,
    firstAired:日期,
    曲风:[字符串]
    网络:字符串,
    概述:字符串,
    等级:数字,
    ratingCount:数字,
    状态:字符串,
    海报:字符串,
    用户:[{
            类型:mongoose.Schema.Types.ObjectId,参考:用户
        }],
    情节:[{
            季节:号码,
            episodeNumber:数字,
            episodeName:字符串,
            firstAired:日期,
            概述:字符串
        }]
});
VAR userSchema =新mongoose.Schema(
    {
        电子邮件:{类型:字符串,唯一的:真正},
        密码:字符串
    });userSchema。pre(保存,函数(下){
    VAR用户=这一点;
    如果(!user.isModified('密码'))返回下一个();
    bcrypt.genSalt(10,函数(ERR,盐){
        如果(ERR)返回下一个(ERR);
        bcrypt.hash(user.password的,盐,功能(ERR,哈希){
            如果(ERR)返回下一个(ERR);
            user.password的哈希值=;
            下一个();
        });
    });
});userSchema.methods.comparePassword =功能(candidatePassword,CB){
    bcrypt.compare(candidatePassword,this.password,功能(ERR,isMatch){
        如果(ERR)返回CB(ERR);
        CB(NULL,isMatch);
    });
}VAR用户= mongoose.model(用户,userSchema);
VAR显示= mongoose.model(显示,showSchema);mongoose.connect('localhost'的);VAR应用=前preSS();app.set('口',process.env.PORT || 3000);
app.use(记录器('开发'));
app.use(bodyParser.json());
app.use(bodyParser.urlen codeD({延长:假}));
app.use(cookieParser());
app.use(会话({秘密:键盘猫}));
app.use(passport.initialize());
app.use(passport.session());
app.use(如press.static(path.join(__目录名称,'公共')));app.listen(app.get('端口'),功能(){
    的console.log('前preSS服务器侦听端口+ app.get('端口'));
});app.get('/ API /显示,功能(REQ,资源,下一个){
    变种查询= Show.find();
    如果(req.query.genre){
        query.where({流派:req.query.genre});
    }否则如果(req.query.alphabet){
        query.where({名:新的RegExp('^'+'['+ req.query.alphabet +']','I')});
    }其他{
        query.limit(12);
    }
    query.exec(函数(ERR,节目){
        如果(ERR)返回下一个(ERR);
        res.send(节目);
    });
});app.get('/ API /显示/:身份证',函数(REQ,资源,下一个){
    Show.findById(req.params.id,函数(ERR,显示){
        如果(ERR)返回下一个(ERR);
        res.send(显示);
    });
});app.post('/ API /显示,功能(REQ,资源,下一个){
    VAR apiKey ='E36B52F7E036AFF3';
    VAR SERIESNAME = req.body.showName
    .toLowerCase()
    .replace(/ /克,_)
    .replace(/ [^ \\ W -​​ ] + /克,'');
    VAR分析器= xml2js.Parser({
        explicitArray:假的,
        normalizeTags:真    });    async.waterfall([
        函数(回调){
            request.GET中('http://thetvdb.com/api/GetSeries.php?seriesname='+ SERIESNAME,功能(错误,响应体){
                如果(错误)返回下一个(错误);
                parser.parseString(机身,功能(错了,结果){
                    如果(!result.data.series){
                        返回res.send(404,{消息:req.body.showName +'未找到'});
                    }
                    VAR seriesId = result.data.series.seriesid || result.data.series [0] .seriesid;
                    回调(ERR,seriesId);
                });
            });
        },
        功能(seriesId,回调){
            request.GET中('http://thetvdb.com/api'+ apiKey +'/系列/+ seriesId +'/all/en.xml'功能(错误,响应体){
                如果(错误)返回下一个(错误);
                parser.parseString(机身,功能(错了,结果){
                    VAR系列= result.data.series;
                    变种发作= result.data.episode;
                    VAR秀=新展({
                        _id:series.id,
                        名称:series.seriesname,
                        airsDayOfWeek:series.airs_dayofweek,
                        airsTime:series.airs_time,
                        firstAired:series.firstaired,
                        流派:series.genre.split('|')过滤器(布尔)。
                        网络:series.network,
                        概述:series.overview,
                        评价:series.rating,
                        ratingCount:series.ratingcount,
                        运行时间:series.runtime,
                        状态:series.status,
                        海报:series.poster,
                        情节:[]
                    });
                    _.each(情节,功能(插曲){
                        show.episodes.push({
                            季节:episode.seasonnumber,
                            episodeNumber:episode.episodenumber,
                            episodeName:episode.episodename,
                            firstAired:episode.firstaired,
                            概述:episode.overview
                        });
                    });
                    回调(ERR,显示);
                });
            });
        },
        功能(显示,回调){
            VAR URL ='http://thetvdb.com/banners/'+ show.poster;
            请求({URL:,编码:空}功能(错误,响应体){
                show.poster ='数据:'+ response.headers ['内涵式'] +';的base64,'+ body.toString('的base64');
                回调(错误,显示);
            });
        }
    ],功能(ERR,显示){
        如果(ERR)返回下一个(ERR);
        show.save(功能(错误){
            如果(ERR){
                如果(ERR。code == 11000){
                    返回res.send(409,{消息:show.name +'已经存在。'});
                }
                返回下一个(ERR);            }
            res.send(200);
        });
    });
});功能ensureAuthenticated(REQ,资源,下一个){
    如果(req.isAuthenticated())下一个();
    别的res.send(401);
};app.use(功能(REQ,资源,下一个){
    如果(req.user){
        res.cookie(用户,JSON.stringify(req.user));
    }
    下一个();
});app.get('*',函数(REQ,RES){
    res.redirect('/#'+ req.originalUrl);
})app.use(函数(ERR,REQ,水库旁){
    console.error(err.stack);
    res.send(500,{消息:err.message});
});


解决方案

修改 VAR的查询= Show.find(); 中/ API /显示了

  VAR的查询= Show.find(函数(ERR,showdata){
    //所有的检查和res.send(节目)到这里
})

只是等待数据,并完成所有的操作(异步)

I have been doing an example based on the TV showTracker and So far I couldn't get any shows into my website. I have been trying so hard to whether I have made a mistake but I still couldn't find anything. So How to I retrieve these information. I have stared this server.js and mongod in separate CMDs and gulp in another CMD I still couldn't get any of the shows. When I see the responses it will show a blank array "[]" like this. So any advice? Help would be most appreciated. (I have host the website yet, thought this would help also to my question). The error in the net debugger says api/shows/ - response = [ ]

Here is my server.jsrespone

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;



var showSchema = new mongoose.Schema({
    _id: Number,
    name: String,
    airsDayOfWeek: String,
    airsTime: String,
    firstAired: Date,
    genre: [String],
    network: String,
    overview: String,
    rating: Number,
    ratingCount: Number,
    status: String,
    poster: String,
    subscribers: [{
            type: mongoose.Schema.Types.ObjectId, ref: 'User'
        }],
    episodes: [{
            season: Number,
            episodeNumber: Number,
            episodeName: String,
            firstAired: Date,
            overview: String
        }]
});


var userSchema = new mongoose.Schema(
    {
        email: { type: String, unique: true },
        password: String
    });

userSchema.pre('save', function (next) {
    var user = this;
    if (!user.isModified('password')) return next();
    bcrypt.genSalt(10, function (err, salt) {
        if (err) return next(err);
        bcrypt.hash(user.password, salt, function (err, hash) {
            if (err) return next(err);
            user.password = hash;
            next();
        });
    });
});

userSchema.methods.comparePassword = function (candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
}

var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);

mongoose.connect('localhost');

var app = express();

app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

app.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

app.get('/api/shows', function (req, res, next) {
    var query = Show.find();
    if (req.query.genre) {
        query.where({ genre: req.query.genre });
    } else if (req.query.alphabet) {
        query.where({ name: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
    } else {
        query.limit(12);
    }
    query.exec(function (err, shows) {
        if (err) return next(err);
        res.send(shows);
    });
});

app.get('/api/shows/:id', function (req, res, next) {
    Show.findById(req.params.id, function (err, show) {
        if (err) return next(err);
        res.send(show);
    });
});

app.post('/api/shows', function (req, res, next) {
    var apiKey = 'E36B52F7E036AFF3';
    var seriesName = req.body.showName
    .toLowerCase()
    .replace(/ /g, '_')
    .replace(/[^\w-]+/g, '');
    var parser = xml2js.Parser({
        explicitArray: false,
        normalizeTags: true

    });

    async.waterfall([
        function (callback) {
            request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + seriesName, function (error, response, body) {
                if (error) return next(error);
                parser.parseString(body, function (err, result) {
                    if (!result.data.series) {
                        return res.send(404, { message: req.body.showName + ' was not found.' });
                    }
                    var seriesId = result.data.series.seriesid || result.data.series[0].seriesid;
                    callback(err, seriesId);
                });
            });
        },
        function (seriesId, callback) {
            request.get('http://thetvdb.com/api' + apiKey + '/series/' + seriesId + '/all/en.xml', function (error, response, body) {
                if (error) return next(error);
                parser.parseString(body, function (err, result) {
                    var series = result.data.series;
                    var episodes = result.data.episode;
                    var show = new Show({
                        _id: series.id,
                        name: series.seriesname,
                        airsDayOfWeek: series.airs_dayofweek,
                        airsTime: series.airs_time,
                        firstAired: series.firstaired,
                        genre: series.genre.split('|').filter(Boolean),
                        network: series.network,
                        overview: series.overview,
                        rating: series.rating,
                        ratingCount: series.ratingcount,
                        runtime: series.runtime,
                        status: series.status,
                        poster: series.poster,
                        episodes: []
                    });
                    _.each(episodes, function (episode) {
                        show.episodes.push({
                            season: episode.seasonnumber,
                            episodeNumber: episode.episodenumber,
                            episodeName: episode.episodename,
                            firstAired: episode.firstaired,
                            overview: episode.overview
                        });
                    });
                    callback(err, show);
                });
            });
        },
        function (show, callback) {
            var url = 'http://thetvdb.com/banners/' + show.poster;
            request({ url: url, encoding: null }, function (error, response, body) {
                show.poster = 'data:' + response.headers['content-type'] + ';base64,' + body.toString('base64');
                callback(error, show);
            });
        }
    ], function (err, show) {
        if (err) return next(err);
        show.save(function (err) {
            if (err) {
                if (err.code == 11000) {
                    return res.send(409, { message: show.name + ' already exists.' });
                }
                return next(err);

            }
            res.send(200);
        });
    });
});

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) next();
    else res.send(401);
};

app.use(function (req, res, next) {
    if (req.user) {
        res.cookie('user', JSON.stringify(req.user));
    }
    next();
});



app.get('*', function (req, res) {
    res.redirect('/#' + req.originalUrl);
})

app.use(function (err, req, res, next) {
    console.error(err.stack);
    res.send(500, { message: err.message });
});

解决方案

Change var query = Show.find(); in /api/shows to

var query  = Show.find(function(err, showdata){
    // all the checking and the res.send(shows) goes here
})

Just wait for data and do all the operation(asynchronous)

这篇关于为什么我从我server.js文件null或[]回应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆