在 Hapi.js 中,我可以重定向到不同的端点并设置状态码吗?
In Hapi.js can I redirect to a different endpoint and set a statusCode?
如果用户未通过身份验证以查看特定路由(例如:/admin
)Auth 会抛出 Boom unorthorized
错误 我希望能够重定向到 /login
但仍然 return 401
HTTP statusCode
.
我们试过以下代码:
const statusCode = request.output.payload.statusCode;
if(statusCode && statusCode === 401) {
return reply.redirect('/login').code(statusCode);
}
当我们删除 .code(statusCode)
时,redirect 会起作用,但我们 ideally like 到 return 401
客户端代码不是 302
(redirect)
或...会是“最佳实践 " 到 return 302
...?
Context: we are developing a little (re-useable) plugin to handle errors in our Hapi App/API and one of the features is to redirect
to /login
when auth fails see: https://github.com/dwyl/hapi-error#redirecting-to-another-endpoint and we want to get it "right" so others can use it!
这是让您伤心的 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);
16 年 12 月编辑:下面的 Kelly Milligan 指出,HapiJS 现在支持使用 reply.redirect().code()
,如果您不希望它发送,则不会发送 302 状态。
如果用户未通过身份验证以查看特定路由(例如:/admin
)Auth 会抛出 Boom unorthorized
错误 我希望能够重定向到 /login
但仍然 return 401
HTTP statusCode
.
我们试过以下代码:
const statusCode = request.output.payload.statusCode;
if(statusCode && statusCode === 401) {
return reply.redirect('/login').code(statusCode);
}
当我们删除 .code(statusCode)
时,redirect 会起作用,但我们 ideally like 到 return 401
客户端代码不是 302
(redirect)
或...会是“最佳实践 " 到 return 302
...?
Context: we are developing a little (re-useable) plugin to handle errors in our Hapi App/API and one of the features is to
redirect
to/login
when auth fails see: https://github.com/dwyl/hapi-error#redirecting-to-another-endpoint and we want to get it "right" so others can use it!
这是让您伤心的 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);
16 年 12 月编辑:下面的 Kelly Milligan 指出,HapiJS 现在支持使用 reply.redirect().code()
,如果您不希望它发送,则不会发送 302 状态。