Home >Web Front-end >JS Tutorial >How to deal with the 302 status code in axios
This time I will bring you the 302 status code in axiosHow to deal with the 302 status code in axios, what are the precautions, the following is a practical case, let’s take a look .
For example, if the browser opens a single page (SPA) application, and the token (or session) expires after a while, after an Ajax request is initiated on the page, the backend returns a 302 status code and jumps to login page. I am using Vue axios and found that axios cannot intercept the 302 request. The following is the processing process.Thinking
google axios 302 handle See two discussions on axios github•https: //github.com/axios/axios/issues/932
• https://github.com/axios/axios/issues/980The conclusion is: browse Ajax request sent by the server, the server returns a 302 status code, and the browser will jump on its own. We cannot directly obtain and customize the processing process through the js library (jquery, axios). We can only wait until the url is obtained after the browser redirects. Corresponding information.axios sends ajax -->So how to solve it? The server needs to cooperate to solve the problem.server returns 302 and location -->
axios Get results
The browser requests a new url -->
The server returns 200 -- >
Brower (ajax and not auth) -->The server determines that it is an ajax request and is not logged in, returning a 401 status code-->
Browser axios intercepts 401 and jumps to /login through js
Solution
On the browser side, axios adds an interceptoraxios.interceptors.response.use((response) => { return response; }, function (error) { if (401 === error.response.status) { window.location = '/login'; } else { return Promise.reject(error); } }); axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';Back-end code, using the flask framework, just look at the process, verify whether the request is ajax and not logged in, and then return the 401 status code
from flask import Blueprint, request, jsonify, make_response, abort from flask_login.utils import current_user, current_app apibp = Blueprint('api', 'api_bp') # 主要逻辑 def bp_login_required(): if not current_user.is_authenticated: if request.is_xhr: abort(401) else: return current_app.login_manager.unauthorized() apibp.before_request(bp_login_required) @apibp.route("/report/domains/<month>/", methods=["GET"]) def monthly_domains(month): return jsonify({}) refI believe you have mastered the method after reading the case in this article. For more exciting content, please pay attention to other related articles on the php Chinese website! Recommended reading:
What are the uses of $emit in vue
Do not use router-link to achieve page jump
The above is the detailed content of How to deal with the 302 status code in axios. For more information, please follow other related articles on the PHP Chinese website!