重定向
重定向
当手动或通过<Link>
元素进行非GET的Inertia请求时,您应确保始终响应正确的Inertia
重定向响应。
例如,如果您的控制器正在创建新用户,则store
端点应返回一个重定向到标准的GET
端点,比如用户的index
页面。Inertia将自动跟随此重定向并相应地更新页面。
class UsersController extends Controller
{
public function index()
{
return Inertia::render('Users/Index', [
'users' => User::all(),
]);
}
public function store(Request $request)
{
User::create(
$request->validate([
'name' => ['required', 'max:50'],
'email' => ['required', 'max:50', 'email'],
])
);
return to_route('users.index');
}
}
303 响应码
在PUT
、PATCH
或者 DELETE
请求后进行重定向时,必须使用 303
响应码,否则后续请求将不会被视为 GET
请求。 303
重定向与 302
重定向非常类似;但是后续请求明确更改为了 GET
.
如果您使用我们官方提供的服务器适配器之一,则所有重定向都会自动转换为 303
.
外部重定向
有时,在处理Inertia请求时需要将其重定向到外部网站甚至是另一个非Inertia端点。可以使用服务器端发起的 window.location
访问来实现,通过 Inertia::location()
方法。
return Inertia::location($url);
Inertia::location()
方法将生成一个带有目标URL的 409 Conflict
响应,并在 X-Inertia-Location
头部中包含该URL. 当客户端接收到此响应时,Inertia将自动执行 window.location = url
的访问。
推荐文章: