Home >Web Front-end >JS Tutorial >How to solve the 302 status code problem in axios
This time I will show you how axios solves the 302 status code problem. What are the precautions for axios to solve the 302 status code problem? 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/980
The 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 -->
server returns 302 and location -->
The browser requests a new url -->
The server returns 200 -- >axios Get results
So how to solve it? The server needs to cooperate to solve the problem.
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 interceptor
axios.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({}) ref
I 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:
Detailed explanation of the steps to use the select built-in component of vue
Avoid re-rendering when using React
The above is the detailed content of How to solve the 302 status code problem in axios. For more information, please follow other related articles on the PHP Chinese website!