在Hapi.js中我可以redirect到一个不同的端点并设置一个statusCode?
如果用户没有通过authentication来查看特定的路由(例如: /admin
),Auth会抛出一个Boom unorthorized
错误我希望能够Boom unorthorized
到/login
但仍然返回401
HTTP statusCode
。
我们已经尝试了下面的代码:
const statusCode = request.output.payload.statusCode; if(statusCode && statusCode === 401) { return reply.redirect('/login').code(statusCode); }
当我们删除.code(statusCode)
时, redirect工作,但我们理想地将401
代码返回到客户端而不是302
( redirect )
或者 …是否是“ 最佳做法 ”返回302
…?
上下文:我们正在开发一个(可重用的 )插件来处理我们的Hapi App / API中的错误,其中一个特性是当auth失败时
redirect
到/login
请参阅https://github.com/dwyl/hapi-错误#redirect到另一个端点 ,我们希望得到它“ 正确 ”,以便其他人可以使用它!
下面是造成你悲伤的HapiJS源代码(lib / response.js:320):
internals.Response.prototype.redirect = function (location) { this.statusCode = 302; this.location(location); this.temporary = this._temporary; this.permanent = this._permanent; this.rewritable = this._rewritable; return this; };
正如你所看到的,通过使用reply.redirect()
Hapi已经在回复302代码。 您需要决定是否在前端回复401和redirect,或使用Hapiredirect,并接受它符合协议标准。
作为最佳做法的答案,是的,当服务器强制执行redirect(302redirect)时,Hapi正在执行所期望的操作。 为了使用401响应,最好的做法是在客户端redirect,就好像您只是简单地导航到路由一样。
作为参考,reply.redirect()函数定义(lib / reply.js:145)很简单
return this.response('').redirect(location);
编辑12月16日:下面的凯利Milligan指出,使用reply.redirect().code()
现在是由HapiJS支持,不会发送302状态,如果你不想要的。
作为这个评论,上面的代码确实设置了状态码。