在Sails.js中使用快速中间件提供静态文件 [英] Using express middleware in Sails.js to serve static files
问题描述
我在0.11.0航行中使用快速中间件时遇到麻烦.我在http.js文件中尝试了以下内容.
I have trouble using the express middleware on sails 0.11.0. I tried the following in http.js file.
module.exports.http = {
customMiddleware: function (app) {
console.log("middleware");
app.use('/test', express.static('****/****/*****/testProject/api/controllers' + '/public/'));
}
};
但是它不起作用,我丢失了一些东西.
But it doesn't work, I am missing something.
推荐答案
对于最新的Sails(0.12),无法直接从config/http.js
调用快速样式app.use(...)
(或作为策略),因为自定义中间件功能参数从function (app)
更改为function (req, res, next)
.这可能就是为什么此处的某些答案不适用于Sails 0.12的原因.
With the latest Sails (0.12), calling express-style app.use(...)
isn't directly possible from config/http.js
(or as a policy) because the custom middleware function parameters changed from function (app)
to function (req, res, next)
. This is probably why some of the answers here don't work with Sails 0.12.
Sails文档和迁移指南中并未明确提及此更改,但请查看 connect-history-api-fallback 为例):
This change isn't clearly mentioned in Sails documentation and migration guides, but looking at Express documentation, we see that app.use(...)
can accept a single function (req, res, next)
argument... so my guess was to assign the parameter to app.use(...)
as a custom middleware in config/http.js
like so (using connect-history-api-fallback as an example):
// config/http.js
var history = require('connect-history-api-fallback');
module.exports.http = {
middleware: {
order: [
'startRequestTimer',
'cookieParser',
'session',
'myRequestLogger',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'router',
'connectHistoryApiFallback', // <==
'www',
'favicon',
'404',
'500'
],
},
// Do this instead of app.use(history())
connectHistoryApiFallback: history()
}
voilà,它就像一种魅力!
And voilà, it works like a charm!
TL; DR 自Sails 0.12起,在config/http.js
中定义的自定义中间件应为function (req, res, next)
类型,而不是function (app)
,因此应调用app.use(someMiddleware)
,而不是app.use(someMiddleware)
. c12>直接在sails.config.http.middleware.order
中.
TL;DR Since Sails 0.12, custom middlewares defined in config/http.js
should be of the type function (req, res, next)
and not function (app)
, so instead of calling app.use(someMiddleware)
, you should place someMiddleware
directly in sails.config.http.middleware.order
.
这篇关于在Sails.js中使用快速中间件提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!