Dealing with 401 Errors: Navigating Redirects using Vue.js and

Currently, I am utilizing Vue.js along with axios in an attempt to create a generic API object as shown below:

import router from './router'
import auth from './auth'
const axios = require('axios')

export const API = axios.create({
  baseURL: `https://my-api.com/`,
  headers: {
    Authorization: auth.getToken()
  }
})

API.interceptors.response.use(null, function (error) {
  if (error.response.status === 401) {
    console.log('Failed to login')
    router.push('/Login')
  }
  return Promise.reject(error)
})

The goal is to automatically redirect users to the Login screen within my single-page application whenever a 401 error code is received. However, despite receiving the console.log message of Failed to login, there is no redirection taking place and no errors are detected in Chrome's Developer Tools.

Answer №1

After encountering a similar issue, I managed to resolve it using the following code snippet:

import router from 'router'
import store from 'store'
...
...
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  console.log(error.response.data)
  if (error.response.status === 401) {
    store.dispatch('logout')
    router.push('/login')
  }
  return Promise.reject(error)
})

Answer №2

If you need to handle errors in your axios post request, here's a simple example:

axios.post("api/endpoint", data)
  .catch(function(error) {
    if (error.response && error.response.status === 401) {
      window.location.href = "login";
    } else {
      // Handle the error in the way that fits your application
    }
  });

Check out the original thread for more information: https://github.com/axios/axios/issues/396#issuecomment-395592900

Answer №3

If you need to integrate an httpClient.js file into your project, you can utilize the following code snippet:

import axios from 'axios';
import {
  authHeader
}
from '../helper'

const baseUrl = 'http://localhost:8811/api/';//local-test
const Api_Path = `${baseUrl}/`;

const httpClient = axios.create({
  baseURL: Api_Path,
  headers: {
    //Authorization: 'Bearer {token}',
    //timeout: 1000, // indicates, 1000ms ie. 1 second
    "Content-Type": "application/json",

  }
})
const authInterceptor = (config) => {
  config.headers['Authorization'] = authHeader();
  return config;
}
const errorInterceptor = error => {


// check if it's a server error
  if (!error.response) {
    //notify.warn('Network/Server error');
    console.error('**Network/Server error');
    console.log(error.response);
    return Promise.reject(error);
  }

  // all the other error responses
  switch (error.response.status) {
    case 400:
      console.error(error.response.status, error.message);
      //notify.warn('Nothing to display', 'Data Not Found');
      break;

    case 401: // authentication error, logout the user
      //notify.warn('Please login again', 'Session Expired');
      console.error(error.response.status, error.message);
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      //router.push('/auth');
      break;

default:
  console.error(error.response.status, error.message);
  //notify.error('Server Error');



 }
  return Promise.reject(error);
}
httpClient.interceptors.request.use(authInterceptor);
httpClient.interceptors.response.use(responseInterceptor, errorInterceptor);

export default httpClient;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When implementing JWT for route authentication, the webpage remains frozen in one spot

Currently, I am in the process of making modifications to a project. The front-end is built using Vue 2.0 and the back-end utilizes Node.js Express. To ensure security, I have implemented the JWT approach by requiring authentication for all pages except th ...

What is the process for inserting text within a .data() method?

I have set up this AJAX request: $.ajax({ method: "GET", url: $('.item').data('query_selector'), dataType: "html" (The ajax call works perfectly, returning something like "item=Mann+Co.+Supply+Crate&quality=6&trad ...

Display the entire dataset retrieved from MongoDB and utilize the doT.js templating engine for rendering

I am facing an issue with extracting data from mongodb and passing it to the view. Despite all my efforts, only one record out of 10000 is showing up instead of all of them. I believe I am very close to resolving this problem but unfortunately, I am stuck. ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Creating an HTML form to collect user data and then automatically saving it to an Excel file stored in a shared Dropbox account

I am looking to extract data from a user form on a website and then automatically save it as an Excel file in a designated Dropbox account once the user clicks submit. Instead of receiving multiple emails every time the form is filled out, I would like t ...

Effortless glide while dragging sliders with JavaScript

In the code below, an Object is looped through to display the object key in HTML as a sliding bar. jQuery(function($) { $('#threshold').change(updateThreshold); function updateThreshold () { var thresholdIndex = parseInt($(&apos ...

Issue with `styles` argument after updating from Material version 4 to 5: MUI

After recently upgrading from Material V4 to V5, I encountered the following error message: MUI: The `styles` argument provided is invalid. You are providing a function without a theme in the context. One of the parent elements needs to use a ThemeProvider ...

using database URL as an AJAX parameter

I am currently working on a Python CherryPy controller that needs to validate a database URL by attempting a connection. However, I am facing challenges with passing the parameter to the method. Below is my AJAX call: $.ajax({ async: false, ty ...

What is the best way to utilize Gulp and Browserify for my JavaScript application?

Looking to modernize my app with a new build system and I could use some guidance. It seems like I need to shift my approach in a few ways. Here's the current structure of my app: /src /components /Base /App.jsx /Pages.jsx /. ...

`Angular RxJS vs Vue Reactivity: Best practices for managing UI updates that rely on timers`

How can you implement a loading spinner following an HTTP request, or any asynchronous operation that occurs over time, using the specified logic? Wait for X seconds (100ms) and display nothing. If the data arrives within X seconds (100ms), display i ...

Ways to break apart a string of text without a regular pattern

Here is the data I am working with: Huawei Y7P Art-L28 (4/64gb) (AAAAAAAAAAAAAA) EXP:02/19/2020 Huawei Y9 prime 2019 (BBBBBBBBBBBBBBB) EXP:07/17/2019 Oppo A31 4gb/128gb (CCCCCCCCCCCCCCC) Vivo Y15 5000mah 4GB/64GB (1901) (DDDDDDDDDDDDDDD) EXP:06/14/2019 I ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...

Use the document.getElementById function in JavaScript to dynamically retrieve elements based on user input in an HTML document. This will

I am currently working towards creating a gallery using pure JavaScript. To start, I am experimenting with a model that involves two buttons - when button #1 is clicked, the string "1.jpg" appears below, and when button #2 is clicked, "2.jpg" is displayed. ...

Troubleshooting Problem with Bootstrap CSS Menu Box Format

I'm having trouble creating a simple menu for my Bootstrap site. What I want to achieve is something like this: This is what I have accomplished so far: I've attempted to write the CSS code but it's not working as expected. Below is the ...

Once an email address is entered, kindly instruct the driver to press the tab key twice for navigation

Adding a user to a website involves entering an email address first, which is then checked against the server's list of users. However, the issue arises when the email validation doesn't occur until clicking outside the input box or pressing tab ...

Trouble with sending data to child components via props

I've been trying to pass a prop to a child component in React, but when I check the props using console log, it doesn't show up at all. Even the key things is missing from the props. Any assistance with this would be greatly appreciated. export ...

Searching through an array based on a specific string

Could someone lend a hand in getting this to function... The code snippet below is functioning const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctN ...

Transformed 700 audio players compartmentalized within a nested tab interface. Optimal tab coding techniques include jquery, ajax

We are currently working on developing a nested tab interface that will include 700 audio players for MP3 files all on the same page within various tabs. However, only one audio player will be visible at a time and will only appear when the tab is clicked. ...

Problem: Vue 3 build does not generate service worker

After adding the "@vue/cli-plugin-pwa": "^4.5.12" to my package.json and setting up workbox configuration in my vue.config.js, I encountered an issue. When running npm run build:prd with the script vue-cli-service build --mode prod.exam ...

Ensuring the Jquery Datepicker restricts selecting dates later than or equal to the start date (

I have a specific requirement where I need to implement two date pickers for entering "From" and "To" dates. The "ToDate" selected should be greater than or equal to the "FromDate" (after selecting a from date, all previous dates should be disabled in the ...