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

What is the best way to trigger the ajax request with the same post parameter upon pressing the browser's back button?

Is there a way to remember the post parameters and resend an AJAX request when the browser back button is pressed? I have searched online and found a couple of methods: Using localsotrage or document.location.hash when the page unloads. Using cookie ...

Migration processes encountering delays due to running nodes

When running migrations in Node, I am encountering a timeout error. The specific error message is: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. Here is the ...

Showing a series of JavaScript countdowns consecutively

I am working on a project where I want to display a second countdown after the first one finishes using meteor. The initial timer code looks like this: sec = 5 @timer = setInterval((-> $('#timer').text sec-- if sec == -1 $('#time ...

What are the advantages of choosing express.js over Ruby on Sinatra?

Currently brainstorming for a social app and contemplating the switch from my initial option, Sinatra/Ruby to express.js/nodejs. My main focus is on the abundance of open source projects in Ruby that can expedite development. Another major consideration i ...

Converting the jQuery $.xajax loadmore feature into a custom XMLHttpRequest JavaScript function

I'm facing challenges while trying to create a XMLHttpRequest loadmore function as compared to using $.ajax. I am uncertain about what I might be missing in my code. Below is the function that is based on a previously working $.ajax version that I ha ...

Successful jQuery Ajax request made without the need for JSON parsing

I find it strange that my experience with jQuery's ajax function is completely different from what I'm used to. Below is the javascript code in question: $.ajax({ url: "/myService.svc/DoAction", type: "GET", dataType: "json", su ...

What are the steps to resolve the issue of "npm ERR! EEXIST: file already exists, rename" occurring with non-existent files?

Welcome to my first question post. (Please be kind if I make mistakes.) I am using node version 5.6.0. For an assignment, I downloaded a JS web app but am encountering an error that is preventing me from working on it: S:\PersonalCloud\jennyly ...

Ensure the correct file extension is chosen when selecting a file for the 'file_field' and display any error messages using Ruby on Rails

I am currently using Ruby on Rails 3 and Prototype, and I need to be able to check the file extension when a file is selected with file_field. I only want to allow files with extensions of .doc or .pdf, any other extensions should display an error. In my ...

Having trouble sending Props between components within a specific route as I keep receiving undefined values

Here is the code for the initial component where I am sending props: const DeveloperCard = ({dev}) => { return ( <Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}> <Button variant="primary">Learn More</Butt ...

How to direct all wildcard paths to a particular route in Next.js

I currently have a single landing page application built with nextJs. I am wondering if it is possible to redirect all paths to specific routes, similar to how we do it in react-router. How can I achieve the same functionality in nextJs? <BrowserRou ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Activating controllers with 2 independent sliders

(Using the WordPress Slider Revolution plugin) I have set up two sliders next to each other - one displaying the service name and description, and the other showing images. The goal is for clicking a specific bullet on the service slider to also trigger t ...

Using the .trim modifier in a Vue.js input field depending on certain conditions

Is there a way to incorporate the .trim modifier in v-model based on certain conditions? We are looking to create a universal input field for our application, where some fields require trimming and others do not. One idea is to include an 'isTrim&apos ...

Vue.js: API request taking too long during mounted lifecycle

I am facing an issue with API data in my Vue js project. The page loads quickly but the data from the API takes more than 5 seconds to load. Strangely, the API response appears very fast in the console. I have implemented the API in a separate file called ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...

Access Flask variable in JavaScript code

Currently working on a CTF challenge, my query is not seeking assistance in solving it, but rather pertains to syntax. The task involves retrieving the secret key from Flask server's configuration. This key is stored within the app.secret_key variable ...

Automatic Form Saving in Angular 4

Seeking to create a form data autosave feature in Angular 4. The functionality should operate as follows: User modifies data in the form -> save request sent to DB. A timer is initiated for 2 seconds. During the 2-second window after the previous save ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

When attempting to access AJAX JSON properties using an index within a promise, the result returned is undefined

I have a quiz app that communicates with my server's API using MongoDB. I am trying to access the response indexes in this way: setTimeout(() => { axios.get('/api/ninjas') .then(function (questions) { var data = questions.d ...