0
我正在尋找一個更快捷的路線模塊化。我有興趣使用諾言來讀取文件,然後返回路線。返回承諾包裹快遞路線到app.use()
下面的代碼:
var express = require('express')
var router = express.Router()
var app = express()
var Promise = require("bluebird")
var fs = Promise.promisifyAll(require("fs"))
function promiseRoute(file){
return fs.readFileAsync(file, "utf8")
.then(JSON.parse)
.then(function(file){
if(!file.url) throw new Error("missing url")
router.get(file.url, function(req, res, next){
return res.redirect("/hello")
})
return router
})
}
app.use(promiseRoute("../file.json"))
var server = app.listen(3000, function() {})
也試過
promiseRoute(path.join(__dirname, "./file.json")).then(app.use)
而且我得到這個錯誤。
throw new TypeError('app.use() requires middleware functions')
而這與承諾。
Unhandled rejection TypeError: Cannot read property 'lazyrouter' of undefined
at use (/project/node_modules/express/lib/application.js:213:7)
at tryCatcher (/project/node_modules/bluebird/js/main/util.js:24:31)
at Promise._settlePromiseFromHandler (/project/node_modules/bluebird/js/main/promise.js:489:31)
at Promise._settlePromiseAt (/project/node_modules/bluebird/js/main/promise.js:565:18)
at Promise._settlePromises (/project/node_modules/bluebird/js/main/promise.js:681:14)
at Async._drainQueue (/project/node_modules/bluebird/js/main/async.js:123:16)
at Async._drainQueues (/project/node_modules/bluebird/js/main/async.js:133:10)
at Immediate.Async.drainQueues [as _onImmediate] (/project/node_modules/bluebird/js/main/async.js:15:14)
at processImmediate [as _immediateCallback] (timers.js:371:17)
也試過這樣:
promiseRoute(path.join(__dirname, "./file.json")).then(function(router){
app.use(function(req, res, next){
return router
})
})
我怎樣才能返回承諾/路線app.use
?
嘿本傑明!謝謝!我試圖在一個文件中有一個路由,並將它傳遞給'app.use',就像這個http://expressjs.com/4x/api.html#router一樣,並且我無法繞回我的頭,在這個承諾內的路線。 – ThomasReggi
'app.use'採用'router'對象或anon'函數(req,res,next)'我不認爲我可以在'function(req,res,next)中返回一個'router'對象。 '它掛在服務器上。 – ThomasReggi