重定向

有时您希望将用户从当前页面重定向到另一个页面。

假设用户尝试访问仪表板页面但尚未登录。我们希望将它们重定向到登录页面,以便对其进行身份验证。

// File: src/routes/dashboard.js
import { component$ } from '@builder.io/qwik';
import { checkAuthorization } from '../auth'; // Your authorization code
import type { DashboardData } from '../types'; // Your types

export const onGet: RequestHandler<DashboardData> = async ({ request, response }) => {
  const isAuthorized = checkAuthorization(request.headers.get('cookie'));

  if (!isAuthorized) {
    // User is not authorized!
    // throw the redirect response to
    // relocate the user to the log-in page
    throw response.redirect('/login');
  } else {
    // ...
  }
};

response.redirect() 函数将 URL作为第一个参数 和可选的状态码作为第二个参数。

throw response.redirect('/login', 301); // Moved Permanently

常见的重定向的状态码:

  • 302: Found. 此响应代码表示请求资源的 URI 已临时更改。将来可能会对 URI 进行进一步的更改。因此,客户端在以后的请求中应该使用相同的 URI。
  • 307: Temporary Redirect. 服务器发送此响应以指示客户端使用先前请求中使用的相同方法从另一个 URI 获取请求的资源。这与 302 Found HTTP 响应代码具有相同的语义,但用户代理不得更改使用的 HTTP 方法:如果在第一个请求中使用了 POST,则必须在第二个请求中使用 POST。
  • 308: Permanent Redirect. 这意味着资源现在永久位于另一个 URI,由 Location HTTP 响应标头指定。这与 301 Moved Permanently HTTP 响应代码具有相同的语义,但用户代理不得更改使用的 HTTP 方法:如果在第一个请求中使用 POST,则必须在第二个请求中使用 POST。

如果您不提供状态代码,Qwik City 将默认为 302 Found 状态。

更多关于重定向状态码的信息参考这里.

Made with ❤️ by