当 fetch 遇到 302 状态码会发生什么?

234 阅读1分钟

当 fetch 遇到 302 状态码,会发生什么?

我用 koa 写了一个小例子来测试 302 状态码。在后端,当接口api/test1接收一个请求,会设置一个 302 状态码并且在响应头中增加重定向的url 信息: api/test2。 后端代码如下:

const Koa = require('koa')
const route = require('koa-route')
const app = new Koa()

const test1 = ctx => {
  ctx.response.redirect('/test2')
}

const test2 = ctx => {
  ctx.response.type = 'json'
  ctx.response.body = { data: 'ddddd!' }
}

app.use(route.get('/api/test1', test1))
app.use(route.get('/api/test2', test2))

app.use(async ctx => {
  ctx.body = 'Hello World'
})

app.listen(9000)

接下来我使用 fetch 向 api/test1 发起一个请求,api/test2会响应信息。

检查网络请求发现,第一个请求 api/test1 返回了 302,然后发起了第二个请求 api/test2

可以用 401 和 403 来处理这种需要认证的接口

  • 后端响应
{  
    "status": "unauthorized",  
    "url": ""
}
  • 前端响应
fetch(url)
  .then(response => {
    if (response.ok) {
    } else if (response.status === 401) {
    } else {
    }
  })
  .catch(error => {
    console.error(error)
  })

总结

  • fetch 不能拦截 302,浏览器会自动从 302 响应的头信息的重定向地址中取到数据。
  • 针对认证的情况,后端可以返回 401 状态码,让前端去检查返回的状态码并据此执行相应操作。