简体   繁体   中英

Why I get a null or [ ] response from my server.js file?

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)

OK Guys, I finally found the answer to the question. It's nothing wrong with the script (server.js). It is because I think it cannot hold the data in the database ( 'localhost:27017/test' ). That is why maybe I'm getting a null response from the TVDB API. Once I changed my database and connect strings to (

'mongodb://nixsiow:abcd1234@ds027479.mongolab.com:27479/nixshowtrackrapp' , It worked like a charm.

So maybe my answer may not explain this properly, or you can look for more details in stack overflow. Thanks for the help guys. I hope that this will help who try to do this tutorial and get stuck on this step.

So final Answer:

mongoose.connect('mongodb://nixsiow:abcd1234@ds027479.mongolab.com:27479/nixshowtrackrapp');

var agenda = require('agenda')({ db: { address: 'mongodb://nixsiow:abcd1234@ds027479.mongolab.com:27479/nixshowtrackrapp'  } }); 

Also Nixsow's website may have a help, it is the most recent update that I found for this tutorial.

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