在happi .js中,我可以重定向到不同的端点并设置statusCode

In Hapi.js can I redirect to a different endpoint and set a statusCode?

本文关键字:端点 statusCode 设置 js happi 重定向 我可以      更新时间:2023-09-26

如果用户未经过身份验证以查看特定路由(例如:/admin) Auth抛出Boom unorthorized错误,我希望能够重定向到/login,但仍然返回401 HTTP statusCode

我们已经尝试了以下代码:

const statusCode =  request.output.payload.statusCode;
if(statusCode && statusCode === 401) {
  return reply.redirect('/login').code(statusCode);
}

当我们删除.code(statusCode)时,重定向工作,但我们将理想的返回401代码给客户端而不是302 (重定向)

…它会是"最佳实践"返回302…?

上下文:我们正在开发一个小的(可重用的)插件来处理我们的Hapi App/API中的错误,其中一个功能是当auth失败时将redirect转换为/login,见:https://github.com/dwyl/hapi-error#redirecting-to-another-endpoint,我们想让它"正确",以便其他人可以使用它!

这是导致你悲伤的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并重定向,还是使用Hapi重定向并接受它符合协议标准。

作为最佳实践位的答案,是的,当服务器强制重定向(302重定向)时,Hapi正在做的正是所期望的。为了使用401响应,最佳实践是在客户端进行重定向,就像您只是正常导航到路由一样。

作为参考,reply.redirect()函数定义(lib/reply.js:145)就是

return this.response('').redirect(location);

编辑12月16日:Kelly Milligan指出,现在HapiJS支持使用reply.redirect().code(),如果你不希望它发送302状态,则不会发送。