在express
中,您可以添加像app.use(cors())
这样的中间件,将其添加到所有端点,但我在firebase示例中找不到类似的东西。以下是如何在每个函数中应用它的示例(见下文(。然而,我想全局应用中间件(cors或其他(,,因为我有很多功能。
import * as cors from 'cors';
const corsHandler = cors({origin: true});
export const exampleFunction= functions.https.onRequest(async (request, response) => {
corsHandler(request, response, () => { return handler(req, res) });
});
在火球中app.use()
的等价物是什么?添加和快速服务器是唯一的选项吗?
使用currying创建一个处理程序,您必须在所有函数中重复它,但这比每次编写中间件更容易:
const applyMiddleware = handler => (req, res) => {
return cors(req, res, () => {
return handler(req, res)
})
}
exports.handler = functions.https.onRequest(applyMiddleware(yourHandler))
Edit,一个更复杂的中间件示例:
const applyMiddleware =
(handler, { authenticatedRoute = false } = {}) =>
(req, res) => {
if (authenticatedRoute) {
const isAuthorized = isAuthenticated(req)
if (!isAuthorized) {
return res.status(401).send('Unauthorized')
}
}
return cors(req, res, () => {
return handler(req, res)
})
}
exports.handler = functions.https.onRequest(
applyMiddleware(yourHandler, { authenticatedRoute: true })
)
import cors from 'cors'
const corsHandler = cors({origin: true});
const applyCORS = handler => (req, res) => {
return corsHandler(req, res, _ => {
return handler(req, res)
})
}
export const firebasefunc = functions.https.onRequest(applyCORS(myhandler))