简体   繁体   English

在重定向之前,为丢失的资源传递正确的HTTP状态代码

[英]Passing the correct HTTP status code for a missing resource, before redirecting

This is a theoretical problem. 这是一个理论问题。 Let's say I have a public user profile page: 假设我有一个公共用户个人资料页面:

mypage.com/users/1 mypage.com/users/1

Before the route /users/{id} is accessed, I check whether the user (so, the resource) exists. 在访问路由/users/{id}之前,我检查用户(即资源)是否存在。 If not, I redirect to homepage: 如果没有,我将重定向到主页:

$user = User::find($id);

if (!isset($user)) {
    return Redirect::to('/');
}

Now, when a user does not exist, the network tab of Chrome dev tools returns 302 Found status and then the redirect to homepage takes place. 现在,当用户不存在时,Chrome开发者工具的网络标签会返回302 Found状态,然后重定向到首页。

Is this the correct status to be set? 这是要设置的正确状态吗? If not, what kind of code should I pass to the redirect to provide information of a missing resource? 如果不是,我应该传递给重定向的哪种代码来提供缺少资源的信息? I don't think it should be 404 , as the route itself might be correct (like /users/12242343534657 ), so - technically - the page might exist. 我不认为它应该是404 ,因为路由本身可能是正确的(例如/users/12242343534657 ),因此-从技术上讲-页面可能存在。 It's just the data that is being requested - doesn't. 只是被请求的数据而并非如此。

What is your experience with this issue? 您对这个问题有什么经验?

All redirects have to use a 3xx status code. 所有重定向都必须使用3xx状态代码。 Here's a list of them 这是他们的清单

In your case that would probably be 302 (or 301, but this will be permanently cached by the browser which could become a problem) 在您的情况下,可能是302(或301,但这将被浏览器永久缓存,这可能会成为问题)

However, should you really redirect to the homepage? 但是,您真的应该重定向到主页吗? I think no. 我觉得不行。 Of course that's just my opinion, but it's really common practice to show a 404 page. 当然,这只是我的意见,但是显示404页确实是很常见的做法。 (Which doesn't just stand for a wrong route but Not found in general) (这不仅代表错误的路线,而且总体上找不到

There are scenarios where redirecting can hurt the user experience. 在某些情况下,重定向可能会损害用户体验。 Imagine you manually entered the address of your site like: 假设您手动输入了您的站点地址,例如:

example.com/usr/lukasgeiter

As you might have noticed, I wrote user wrong. 您可能已经注意到,我给user写的错误。 With a redirect I'd have to type everything again. 通过重定向,我将不得不再次键入所有内容。 If you stay on the site and display an error message I can correct my spelling error and load the correct page. 如果您留在网站上并显示错误消息,我可以纠正我的拼写错误并加载正确的页面。

Also it's much more clear to the user what happend that way. 而且,对于用户而言,这种方式发生的事情也更加清楚。 Obviously you can put a big link to home on the error page so the user knows what to do next ;) 显然,您可以在错误页面上放置一个指向主页的大链接,以便用户知道下一步该怎么做;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM