2016-08-22 215 views
0

我首先創建了一個API,使用Node/Express來從大多數程序員所做的「天真」方式中學習。這是運作良好,我決定嘗試快遞發電機。快速生成器 - 類型錯誤:app.set不是函數

設置完畢後,應用程序正常工作。

我添加了我的一堆代碼(主要是在app.js和導入幾條路線來嘗試),我沒有改變任何設置快遞的bin/www中的任何東西。

但在推出我得到這個錯誤在這個特別的文件斌/ WWW指出:

app.set('port', port); 
    ^

TypeError: app.set is not a function 

我不知道爲什麼這部分代碼自動生成不希望現在的工作。

在這裏,2個委託人文件

斌/ WWW:(產生-不變)

#!/usr/bin/env node 

/** 
* Module dependencies. 
*/ 

var app = require('../app'); 
var debug = require('debug')('API:server'); 
var http = require('http'); 

/** 
* Get port from environment and store in Express. 
*/ 

var port = normalizePort(process.env.PORT || '3000'); 
app.set('port', port); 

/** 
* Create HTTP server. 
*/ 

var server = http.createServer(app); 

/** 
* Listen on provided port, on all network interfaces. 
*/ 

server.listen(port); 
server.on('error', onError); 
server.on('listening', onListening); 

/** 
* Normalize a port into a number, string, or false. 
*/ 

function normalizePort(val) { 
    var port = parseInt(val, 10); 

    if (isNaN(port)) { 
    // named pipe 
    return val; 
    } 

    if (port >= 0) { 
    // port number 
    return port; 
    } 

    return false; 
} 

/** 
* Event listener for HTTP server "error" event. 
*/ 

function onError(error) { 
    if (error.syscall !== 'listen') { 
    throw error; 
    } 

    var bind = typeof port === 'string' 
    ? 'Pipe ' + port 
    : 'Port ' + port; 

    // handle specific listen errors with friendly messages 
    switch (error.code) { 
    case 'EACCES': 
     console.error(bind + ' requires elevated privileges'); 
     process.exit(1); 
     break; 
    case 'EADDRINUSE': 
     console.error(bind + ' is already in use'); 
     process.exit(1); 
     break; 
    default: 
     throw error; 
    } 
} 

/** 
* Event listener for HTTP server "listening" event. 
*/ 

function onListening() { 
    var addr = server.address(); 
    var bind = typeof addr === 'string' 
    ? 'pipe ' + addr 
    : 'port ' + addr.port; 
    debug('Listening on ' + bind); 
} 

app.js:

// Module dependencies 
const express = require('express'); 
const cluster = require('express-cluster'); // fork the service on different thread 
const helmet = require('helmet'); // Secure HTTP header 
const cors = require('cors'); 
const path = require('path'); 
const bodyParser = require('body-parser'); // Help to easily parse the body of req/res 
const port = process.env.PORT || 3000; 
const mongoose = require('mongoose'); // Manage MongoDB request 

cluster(function(worker) { 
    var app = express(); 

    // MongoDB config 
    const config = require('./misc/config/index'); // Config variable like MongoDB credential 
    mongoose.Promise = global.Promise; 
    mongoose.connect(config.getDBConnectionString()); // Config to cnx to mongodb 
    // mongoose.connect(config.getDBConnectionString(), { config: { autoIndex: false } }); 

    // Middleware 
    app.use(bodyParser.json()); 
    app.use(bodyParser.urlencoded({extended: true})); 
    app.use(helmet.frameguard()); // Default Value - Help to secure request by putting some setting in the header 
    app.use(cors()); // Handling Cross Origin Ressource Sharing 

    // Logfile 
    const log = require('./misc/log/log'); 
    app.use(log); 

    // Config Landingpage to/
    app.use('/assets', express.static(path.join(__dirname, 'public'))); 
    app.set('view engine', 'ejs'); 

    // Entry point 
    const entryPoint = require('./routes/entryPoint'); 
    app.get('/', entryPoint.index); 
    app.get('/api', function (req, res) { 
    res.redirect(301, '/'); 
    }) 

    // API Key handler 
    const auth = require('./misc/auth/auth'); 
    app.use(auth); 

    // List 
    const list = require('./routes/list/listRouter'); // Get List endpoints 
    // app.use('/api/list', list); 

    // Map 
    const map = require('./routes/map/mapRouter'); // Get List endpoints 
    // app.use('/api/map', map); 

    module.exports = app; 
}, {count: 2}) 

我導出的應用程序,其包括快速()。所以我在這裏錯過了一些東西,但我沒有看到什麼。

+0

'cluster()'將是異步的,所以在導入的時候還沒有任何東西被導出。如果您需要在多個CPU上運行您的應用程序,可能值得看看['pm2'](http://pm2.keymetrics.io/)。 – robertklep

+0

是的,我只是嘗試刪除羣集(),它的工作原理。謝謝pm2,但我聽說pm2正在消耗很多資源? – Ragnar

+0

pm2可能有點兒碰巧,有些人有很多問題,大多數人(包括我自己)都沒有。你總是可以從等式中移除'./ bin/www',它不提供_that_多功能,所以你可以把它移動到'app.js'(並繼續使用'cluster()')。 – robertklep

回答

2

的問題是由這種設置造成的:

cluster(function(worker) { 
    var app = express(); 
    ... 
    module.exports = app; 
}, { ... }); 

因爲cluster將調用「工人功能」異步,出口是異步完成的爲好,這是爲時已晚bin/www。除此之外,工作人員功能將運行在一個單獨的過程中,這也使事情變得複雜。

由於bin/www在做什麼方面相對簡單,您可以選擇將其內容(或至少它的作用要點)移動到app.js,然後以node app.js開始您的應用。你甚至可以用一個簡單的腳本替換bin/www

#!/usr/bin/env node 

require('../app'); 

或者,您也可以留下您的代碼按並依靠外部程序來提供負載在可用CPU的平衡。一個流行的解決方案是pm2,雖然它不適合每個人(看起來似乎是碰碰運氣)。

如果你需要傳遞環境變量,你可以在命令行中這樣做:

$ env API_KEY=XXX pm2 start app.js 

或者創建a configuration file爲您的應用程序。

還有一個名爲dotenv的軟件包,可讓您的Node應用程序直接從文件讀取環境變量。