记录工作中早该加深印象的一个小case: ajax请求不能显式拦截 302响应。
我们先来看一个常规的登录case:
- 浏览器请求资源,服务器发现该请求未携带相关凭据(cookie或者token)
- 服务器响应302,并在响应头Location写入重定向地址, 指示浏览器跳转到登录页
- 浏览器跳转到登录页,提交身份信息,回调到原业务站点,服务端利用Set-Cookie响应头种下cookie或者token
Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.
When you make an HTTP request with axios, the library returns a promise. If the request is successful (i.e. the server responds with a 2xx status code), the promise will be resolved and the then() callback will be called with the response data. On the other hand, if the request fails (i.e. the server responds with a 4xx or 5xx status code), the promise will be rejected and the catch() callback will be called with the error.
- axios在浏览器发起的是ajax请求
- axios默认认为只有2xx状态码是成功的响应, 会进入promise的resolved回调函数, 本case第一次会收到302重定向响应, 故添加ValidateStatus配置尝试resolved302响应。
伪代码如下:
axios.request({
method:'get',
url:'/login',
validateStatus: function (status) {
return status >= 200 && status < 300 || status === 302;
},
}).then((resp)=> {
if resp.status ===302 {
window.location.href = resp.headers['Location']
}else{
var userInfo = JSON.parse(
decodeURIComponent(
resp.data.msg || ""
) || "{}"
)
this.setState({
userInfo
})
}
})
实际上以上ajax请求收到的302响应并不能被显式拦截,上面的resp实际是redirect之后的页面的响应体。
核心在于:所有浏览器都遵循了ajax标准:readystatus=2, All redirects (if any) have been followed and all headers of a response have been received.
翻译下来就是 : ajax请求收到的响应如果有重定向,必然是重定向逻辑走完之后的响应。
对于这个常规的case, github上给出的思路是: 针对不同类型的http请求,服务端给出不同的状态码。
故我们的思路是[区分常规http请求和ajax脚本请求]。
// ajax不能处理3xx请求,故根据实际的http请求类型区分
if c.Request.Header["X-Requested-With"] != nil && c.Request.Header["X-Requested-With"][0] == "XMLHttpRequest" {
c.JSON(http.StatusForbidden, gin.H{
"code": 403,
"msg": redirectUrl})
}else {
c.Redirect(http.StatusFound, redirectUrl)
}
如果是ajax请求,返回4xx json响应,让浏览器主动重定向。
// 给ajax请求种植特征请求头
axios.defaults.headers.common['X-Requested-With']="XMLHttpRequest";
axios.request({
method: 'get',
url: '/login',
validateStatus: function (status) {
return status >= 200 && status < 300 || status === 403;
},
}).then((resp)=> {
if (resp.status===200 && resp.data.code === 200) {
......
}else{ // 收到信号,自行完成跳转
window.location.href = resp.data.msg
}
})
总结
根据Ajax标准,ajax请求不能拦截302响应,若服务器返回302,ajax请求收到的是302重定向之后的服务器响应。
变通方案 : 我们可以返回 非3xx的响应,让前端收到信号,自行完成跳转。