API Node.js работает локально, но не на Heroku

По какой-то безумной причине мой локальный сервер Node работает, когда я тестирую с почтальоном, но когда я загружаю в Heroku, я получаю следующую ошибку:

at=error code=H12 desc="Request timeout" method=POST path="/api/messages" host=test.herokuapp.com request_id=big_number_here fwd="my_ip_address" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https

Просто кажется, что время истекло. Я протестировал другой маршрут, обычный маршрут переднего конца, и он загружается правильно. Мой код ниже:

app.js

var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);

app_api / routes

var express = require('express');
var router = express.Router();

var ctrlMessages = require('../controllers/messages');

// Messages
router.post('/messages', ctrlMessages.messagesCreate);


module.exports = router;

ИЗМЕНИТЬ

messages.js (добавление кода контроллера)

var mongoose = require('mongoose');
var Msg = mongoose.model('Messages');

// mongoose.set('debug', true); // TESTING

var sendJsonResponse = function(res, status, content) {
    res.status(status);
    res.json(content);
};

/* POST a new location */
/* /api/messages */
module.exports.messagesCreate = function(req, res) {
    Msg.create({
        msg1: req.body.msg1,
        msg2: req.body.msg2
    }, function(err, msg) {
        if (err) {
            console.log(err);
            sendJsonResponse(res, 400, err);
        } else {
            console.log(err);
            sendJsonResponse(res, 201, msg);
        }
    });
};

Модель messages.js

var mongoose = require('mongoose');

var msgdata = new mongoose.Schema({
    msg1: {
        type: String,
        required: true,
    },
    msg2: {
        type: String,
        required: true
    },
    createdOn: {
        type: Date,
        "default": Date.now
    }
});

mongoose.model('Messages', msgdata);

Коннектор БД db.js

var mongoose = require('mongoose');
var gracefulShutdown;
var dbURI = 'mongodb://locationToMyMongoDB';


if (process.env.NODE_ENV === 'production') {
    dbURI = process.env.MONGOLAB_URI;
}
mongoose.connect(dbURI);

// Emulate SIGINT signal for Windows
var readLine = require('readline');
if (process.platform === "win32") {
    var rl = readLine.createInterface ({
        input: process.stdin,
        output: process.stdout
    });
    rl.on ('SIGINT', function() {
        process.emit ("SIGINT");
    });
}

mongoose.connection.on('connected', function() {
    console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
    console.log('mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
    console.log('Mongoose disconnected');
});

gracefulShutdown = function(msg, callback) {
    mongoose.connection.close(function() {
        console.log('Mongoose disconnected through ' + msg);
        callback();
    });
};

// For nodemon restarts
process.once('SIGUSR2', function() {
    gracefulShutdown('nodemon restart', function() {
        process.kill(process.pid, 'SIGUSR2');
    });
});
// For app termination
process.on('SIGINT', function() {
    gracefulShutdown('app termination', function() {
        process.exit(0);
    });
});
// For Heroku app termination
process.on('SIGTERM', function() {
    gracefulShutdown('Heroku app shutdown', function() {
        process.exit(0);
    });
});

// BRING IN SCHEMAS & MODELS
require('./messages');

person Kenny    schedule 11.03.2017    source источник
comment
Вы можете опубликовать исходный код ctrlMessages?   -  person Michał Młoźniak    schedule 11.03.2017
comment
Привет, я добавил код контроллера внизу.   -  person Kenny    schedule 11.03.2017
comment
Вы пробовали вставлять какие-то сообщения журнала, чтобы увидеть, выполняется ли какой-либо код?   -  person toddg    schedule 11.03.2017
comment
@toddg нет, но это хорошая идея, я должен это сделать.   -  person Kenny    schedule 11.03.2017


Ответы (2)


Это довольно забавное, но такое простое решение:

отрывок из db.js

...
var dbURI = 'mongodb://locationToMyMongoDB';

if (process.env.NODE_ENV === 'production') {
    dbURI = process.env.MONGOLAB_URI;
}
...

Я использовал жестко закодированную переменную dbURI и не указывал ее как переменную среды, поэтому мой код проверял, существует ли process.env.MONGOLAB_URI, но этого не произошло.

Я просто закомментировал эту строку, и она отлично сработала!

person Kenny    schedule 11.03.2017

Много сообщений о производственной / Heroku версии API?

Код ошибки H12 означает, что истекло время ожидания запроса (см. https://devcenter.heroku.com/articles/error-codes#h12-request-timeout), поскольку Heroku устанавливает максимальное ограничение в 30 секунд.

Попробуйте разбить конечную точку на страницы или вернуть меньше данных.

person gwcodes    schedule 11.03.2017
comment
Привет, спасибо за ответ. Честно говоря, данных передается не так много, как всего несколько слов. Я обновил OP своим кодом контроллера, если это помогает. - person Kenny; 11.03.2017