Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

302 redirect 原理 #8

Open
BUPTlhuanyu opened this issue Feb 26, 2023 · 0 comments
Open

302 redirect 原理 #8

BUPTlhuanyu opened this issue Feb 26, 2023 · 0 comments

Comments

@BUPTlhuanyu
Copy link
Owner

BUPTlhuanyu commented Feb 26, 2023

ctx.redirect(url);
koa 会设置响应头 Location 为 url,并且 status 为 302;浏览器识别返回码为 302 重定向,读取响应头 location 的值,并发出请求,注意这里并不会改变地址栏的 url,请求可以通过 network 面板查看。

koa 源码如下:

  redirect(url, alt) {
    // location
    if ('back' == url) url = this.ctx.get('Referrer') || alt || '/';
    this.set('Location', url);

    // status
    if (!statuses.redirect[this.status]) this.status = 302;

    // html
    if (this.ctx.accepts('html')) {
      url = escape(url);
      this.type = 'text/html; charset=utf-8';
      this.body = `Redirecting to <a href="${url}">${url}</a>.`;
      return;
    }

    // text
    this.type = 'text/plain; charset=utf-8';
    this.body = `Redirecting to ${url}.`;
  },
@BUPTlhuanyu BUPTlhuanyu changed the title 302 redirect 302 redirect 原理 Feb 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant