Node.js API 在本地工作但不在 Heroku 上工作

Node.js API working locally but not on Heroku

由于某些疯狂的原因,当我使用邮递员进行测试时,我的本地节点服务器正在运行,但是当我上传到 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');

production/Heroku版本的API有很多留言吗?

H12 错误代码表示请求已超时(请参阅 https://devcenter.heroku.com/articles/error-codes#h12-request-timeout),因为 Heroku 强制执行 30 秒的最大限制。

尝试对端点进行分页,或返回较少的数据。

所以这有点有趣,但是这样一个简单的解决方案:

摘自 db.js

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

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

我使用的是硬编码的 dbURI 变量,没有将其列为环境变量,因此我的代码正在检查 process.env.MONGOLAB_URI 是否存在,但它不存在。

我简单地评论了那行,它完美地工作了!