如何在Loopback 4中使用有状态请求? [英] How to use stateful requests in Loopback 4?
问题描述
在v3中,我们可以在基础Express上定义中间件,例如 express-session ,以添加请求对象上的session
属性.
In v3, we could define middlewares on underlying Express, such as express-session, to add a session
property on requests objects.
在v4中,似乎没有与此等效的东西,并且基础Express也没有公开.
In v4, it looks like there is no equivalent for this, and the underlying Express is not exposed.
我正在将身份验证提供程序从v3迁移到v4,因此我陷入了困境.我该怎么办?
I am migrating an authentication provider from v3 to v4 and I'm stuck because of that. How can I do?
我尝试了以下解决方法,但没有成功:
I tried the following workaround but it didn't work:
import { MyApplication } from './application';
import { ApplicationConfig } from '@loopback/core';
const expressSession = require('express-session');
export { MyApplication };
export async function main(options: ApplicationConfig = {}) {
const app = new MyApplication (options);
// @ts-ignore
app.restServer._expressApp.use(expressSession);
await app.boot();
await app.start();
const url = app.restServer.url;
console.log(`Server is running at ${url}`);
console.log(`Try ${url}/ping`);
return app;
}
推荐答案
来自LoopBack团队的问候:)
Hello from the LoopBack team :)
我们尚未考虑支持HTTP会话和有状态请求.理想情况下,会话处理应作为新的Sequence操作实现-请参见 Sequence文档
We haven't looked into supporting HTTP sessions and stateful requests yet. Ideally, session handling should be implemented as a new Sequence action - see Sequence docs.
class MySequence {
// skipping constructor with dependencies to be injected
async handle(context: RequestContext) {
try {
// the following line is new
const session = this.restoreSession(context);
// the default sequence continues here
const route = this.findRoute(context.request);
const params = await this.parseParams(context.request, route);
const result = await this.invoke(route, params);
await this.send(context.response, result);
} catch (error) {
await this.reject(context, error);
}
}
}
序列动作restoreSession
应该:
- 检查请求中是否存在任何会话Cookie
- 如果提供了cookie,则加载会话,否则可以创建一个新的cookie?
- 将会话绑定到我们的 Context 中,以便控制器等其他地方也可以通过依赖注入 接收会话
- check if there are any session cookies present in the request
- load the session if a cookie was provided, maybe create a new one otherwise?
- bind the session in our Context so that other places like controllers can receive the session via Dependency Injection
您能否在 loopback-next a>以便我们在那里讨论实施细节?
Could you please open a new GitHub issue (a feature request) in loopback-next so that we can discuss implementation specifics there?
这篇关于如何在Loopback 4中使用有状态请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!