Home Web Front-end JS Tutorial How to solve the 302 status code problem in axios

How to solve the 302 status code problem in axios

May 25, 2018 pm 02:15 PM
axios state question

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';
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Connection status in standby: Disconnected, reason: NIC Compliance Connection status in standby: Disconnected, reason: NIC Compliance Feb 19, 2024 pm 03:15 PM

"The connection status in the event log message shows Standby: Disconnected due to NIC compliance. This means that the system is in standby mode and the network interface card (NIC) has been disconnected. Although this is usually a network issue , but can also be caused by software and hardware conflicts. In the following discussion, we will explore how to solve this problem." What is the reason for standby connection disconnection? NIC compliance? If you see the "ConnectivityStatusinStandby:DisConnected,Reason:NICCompliance" message in Windows Event Viewer, this indicates that there may be a problem with your NIC or network interface controller. This situation is usually

How to set Momo status How to set Momo status Mar 01, 2024 pm 12:10 PM

Momo, a well-known social platform, provides users with a wealth of functional services for their daily social interactions. On Momo, users can easily share their life status, make friends, chat, etc. Among them, the setting status function allows users to show their current mood and status to others, thereby attracting more people's attention and communication. So how to set your own Momo status? The following will give you a detailed introduction! How to set status on Momo? 1. Open Momo, click More in the lower right corner, find and click Daily Status. 2. Select the status. 3. The setting status will be displayed.

How to check server status How to check server status Oct 09, 2023 am 10:10 AM

Methods to view server status include command line tools, graphical interface tools, monitoring tools, log files, and remote management tools. Detailed introduction: 1. Use command line tools. On Linux or Unix servers, you can use command line tools to view the status of the server; 2. Use graphical interface tools. For server operating systems with graphical interfaces, you can use the graphics provided by the system. Use interface tools to view server status; 3. Use monitoring tools. You can use special monitoring tools to monitor server status in real time, etc.

Clustering effect evaluation problem in clustering algorithm Clustering effect evaluation problem in clustering algorithm Oct 10, 2023 pm 01:12 PM

The clustering effect evaluation problem in the clustering algorithm requires specific code examples. Clustering is an unsupervised learning method that groups similar samples into one category by clustering data. In clustering algorithms, how to evaluate the effect of clustering is an important issue. This article will introduce several commonly used clustering effect evaluation indicators and give corresponding code examples. 1. Clustering effect evaluation index Silhouette Coefficient Silhouette coefficient evaluates the clustering effect by calculating the closeness of the sample and the degree of separation from other clusters.

Teach you how to diagnose common iPhone problems Teach you how to diagnose common iPhone problems Dec 03, 2023 am 08:15 AM

Known for its powerful performance and versatile features, the iPhone is not immune to the occasional hiccup or technical difficulty, a common trait among complex electronic devices. Experiencing iPhone problems can be frustrating, but usually no alarm is needed. In this comprehensive guide, we aim to demystify some of the most commonly encountered challenges associated with iPhone usage. Our step-by-step approach is designed to help you resolve these common issues, providing practical solutions and troubleshooting tips to get your equipment back in peak working order. Whether you're facing a glitch or a more complex problem, this article can help you resolve them effectively. General Troubleshooting Tips Before delving into specific troubleshooting steps, here are some helpful

Detailed explanation of the five states of Java threads and state transition rules Detailed explanation of the five states of Java threads and state transition rules Feb 19, 2024 pm 05:03 PM

In-depth understanding of the five states of Java threads and their conversion rules 1. Introduction to the five states of threads In Java, the life cycle of a thread can be divided into five different states, including new state (NEW), ready state (RUNNABLE), Running status (RUNNING), blocking status (BLOCKED) and termination status (TERMINATED). New state (NEW): When the thread object is created, it is in the new state. At this point, the thread object has allocated enough resources to perform the task

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

Label acquisition problem in weakly supervised learning Label acquisition problem in weakly supervised learning Oct 08, 2023 am 09:18 AM

The label acquisition problem in weakly supervised learning requires specific code examples. Introduction: Weakly supervised learning is a machine learning method that uses weak labels for training. Different from traditional supervised learning, weakly supervised learning only needs to use fewer labels to train the model, rather than each sample needs to have an accurate label. However, in weakly supervised learning, how to accurately obtain useful information from weak labels is a key issue. This article will introduce the label acquisition problem in weakly supervised learning and give specific code examples. Introduction to the label acquisition problem in weakly supervised learning:

See all articles