The scenario of incorrect authentication in Vuex using Axios resulted in a 404 error due to an

While attempting to authenticate with an API that I'm utilizing, I encountered an issue during login where I received the following response: "Failed to load resource: the server responded with a status of 404 (Not Found) [http://localhost:8080/localhost:5000/api/login]"

It seems like the issue might be related to axios, as it is combining my local Vue application address with the API address for the request.

In main.js:

import axios from 'axios'
Vue.use(axios)
axios.defaults.baseURL = process.env.VUE_APP_API; //(http://localhost:5000/api

In modules/auth.js:

import { AUTH_REQUEST, AUTH_ERROR, AUTH_SUCCESS, AUTH_LOGOUT } from '../actions/auth'
import { USER_REQUEST } from '../actions/user'
import axios from 'axios'

const state = { token: localStorage.getItem('user-token') || '', status: '', hasLoadedOnce: false }

const getters = {
  isAuthenticated: state => !!state.token,
  authStatus: state => state.status,
}

const actions = {
  [AUTH_REQUEST]: ({commit, dispatch}, user) => {
    return new Promise((resolve, reject) => {
     commit(AUTH_REQUEST)
  axios({url: '/login', data: user, method: 'POST'})
  .then(resp => {
    localStorage.setItem('user-token', resp.token)
    // Set the header of your ajax library to the token value here.
    axios.defaults.headers.common['Authorization'] = resp.token
    commit(AUTH_SUCCESS, resp)
    dispatch(USER_REQUEST)
    resolve(resp)
  })
  .catch(err => {
    commit(AUTH_ERROR, err)
    localStorage.removeItem('user-token')
    reject(err)
  })
})
},
}

const mutations = {
  [AUTH_REQUEST]: (state) => {
  state.status = 'loading'
  },
  [AUTH_SUCCESS]: (state, resp) => {
    state.status = 'success'
    state.token = resp.token
    state.hasLoadedOnce = true
  },
  [AUTH_ERROR]: (state) => {
  state.status = 'error'
  state.hasLoadedOnce = true
  },
  [AUTH_LOGOUT]: (state) => {
    state.token = ''
  }
}

export default {
 state,
 getters,
 actions,
 mutations,
}

In Login.vue:

  methods: {
    login() {
      const { username, password } = this
      this.$store.dispatch(AUTH_REQUEST, { username, password }).then(() => {
      this.$router.push('/')
   })
    },

Answer №1

Avoid defining axios in the main file altogether.

It's worth noting that axios isn't a vue plugin, so using Vue.use(axios) won't have any effect.

In your auth.js file, you can set up an instance like this:

const axios = require('axios');

const axiosInstance = axios.create({
  baseURL: process.env.VUE_APP_API
});

When working with actions, make sure to use the axios instance instead of axios itself:

const actions = {
  [AUTH_REQUEST]: ({commit, dispatch}, user) => {
    return new Promise((resolve, reject) => {
     commit(AUTH_REQUEST)
  axiosInstance({url: '/login', data: user, method: 'POST'})
  .then(resp => {
    localStorage.setItem('user-token', resp.token)
    // Set the ajax library header to the token value.
    axios.defaults.headers.common['Authorization'] = resp.token
    commit(AUTH_SUCCESS, resp)
    dispatch(USER_REQUEST)
    resolve(resp)
  })
  .catch(err => {
    commit(AUTH_ERROR, err)
    localStorage.removeItem('user-token')
    reject(err)
  })
})

You might encounter header update issues after creating the instance, so consider using dynamic methods to workaround:

const axiosInstance = axios.create({
  baseURL: process.env.VUE_APP_API,
  headers: {
    Authorization: {
      toString () {
        return `Bearer ${localStorage.getItem('user-token')}`
      }
    }
  }
})

Another approach is to create a new request for each call:

const actions = {
  [AUTH_REQUEST]: ({ commit, dispatch }, user) => {
    return new Promise((resolve, reject) => {
      const axiosInstance = axios.create({
        baseURL: process.env.VUE_APP_API
      });
      commit(AUTH_REQUEST)
      axiosInstance({
          url: '/login',
          data: user,
          method: 'POST'
        })
        .then(resp => {
          localStorage.setItem('user-token', resp.token)
          // Setting the Ajax library header to the token value.
          axios.defaults.headers.common['Authorization'] = resp.token
          commit(AUTH_SUCCESS, resp)
          dispatch(USER_REQUEST)
          resolve(resp)
        })
        .catch(err => {
          commit(AUTH_ERROR, err)
          localStorage.removeItem('user-token')
          reject(err)
        })
    })
  },
  [SECURE_REQUEST]: ({ commit, dispatch }, user) => {
    return new Promise((resolve, reject) => {
      const axiosInstance = axios.create({
        baseURL: process.env.VUE_APP_API,
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('user-token')
        }
      });
      commit(SECURE_REQUEST)
      axiosInstance({
          url: '/getData',
          data: user,
          method: 'POST'
        })
        // ...
    })
  },
}

An alternative method I currently use involves configuring devServer.proxy. This option requires Vue-Cli-3 and assumes the static bundle will run on the same server as your API.

For additional solutions, refer to: https://github.com/axios/axios/issues/1383#issuecomment-405900504

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

JavaScript - Issue with the OnClick event not triggering

I encountered an issue while trying to change the class of an element using pure Javascript upon clicking it. Even though I have used similar code successfully in the past, this particular instance did not work as expected. Here is the relevant part of the ...

Error: It seems like Material UI has updated their export structure and now `makeStyles` is no longer available in the

The export of makeStyles from @mui/material/styles has been deprecated. Despite importing from @mui/styles throughout my project, this error continues to appear. I have already tried removing the node_modules folder and reinstalled, but the issue persis ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...

What steps can be taken to address issues with the csv to json conversion module?

I'm struggling to correctly match the title and genre in my module. There's a issue in the csv_json module where it doesn't handle properties properly, especially when the title includes "The". //csv file movieId,title,genre 1,"American P ...

Adjusting the D3 SVG zoom to focus on a specific rectangle within a group (<g>) at a varying angle

I am working with an <svg> that contains background images and various rectangles positioned correctly within the svg. The rectangles are grouped using <g> tags with translation values and specific rotation angles assigned to each one. My goal ...

Encountering the error message "do not mutate props directly" while also trying to render a button

Whenever I try to pass my prop to a component, I encounter an error message. The prop in question is used to display a button element in the payment section. However, there are certain components where this button should not be displayed. Unfortunately, wh ...

Unified sign on between two apps within a singular Azure AD B2C tenant (Next.js and wikiJS)

I am experiencing an issue with two apps registered in the same Azure AD B2C tenant. App1 is a Next.js app utilizing Azure AD B2C authentication using msal-react App2 is a WikiJS app equipped with two authentication strategies (customers and employees). ...

Problem with Sending POST Requests in ExpressJS

Having trouble with a POST request in Postman resulting in a long loading time followed by a Could not get any response error message? No errors are showing up in the terminal. Could there be an issue with how I am saving the POST data, especially in my /b ...

Searching for all choices within a select dropdown using Selenium and Python

There's a website called noveltop (.net) that hosts web novels, and on each chapter page, there is a dropdown menu where you can select the chapter you want to jump to. I've been using Selenium with Python and the Firefox (or Chrome) driver to e ...

Using Node.js, we can create a program that makes repetitive calls to the same API in a

My task involves making recursive API calls using request promise. After receiving the results from the API, I need to write them into an excel file. Below is a sample response from the API: { "totalRecords": 9524, "size": 20, "currentPage": 1, "totalPage ...

Issue with Jquery focus on dropdown not working

I am facing an issue with setting up the dropdown feature for my list. It's similar to ul li:hover ul li. What I'm trying to achieve is something like ul li:focus ul li in jQuery because I don't think it can be done using CSS. The desired ou ...

The issue with AngularJS 2-way-binding failing to refresh

Recently, I experimented with angularJS in conjunction with a range-slider-directive that can be found here: https://github.com/supertorio/angular-rangeslider-directive Initially, everything worked well while using the data-model solely within my HTML pa ...

Maximizing the full potential of a JavaScript menu using WebDriver

I am facing a challenge in clicking a button on a website using WebDriver that utilizes JavaScript to expand a menu and display additional links: <div id="menu"> <div id="security_bt" class="advanced_white_close_button" onclick="open_or_close_sub ...

Ramda represents a distinct alternative to traditional vanilla JavaScript

I'm feeling a bit confused about how Ramda really works. I found this code and I'm not entirely sure how it functions. const render = curry( (renderer, value) => is(Function, renderer) && renderer(value) ); I just need to grasp an ...

Display new information within a div element seamlessly without refreshing the page

Just a heads-up, I'm new to HTML development... Currently working on a website using Bootstrap. There are some buttons on the left side shown in the screenshot, and my goal is to update the content on the right without having to reload the entire pag ...

"Troubleshooting 404 error when using Vue.js and vue.config

I'm currently following the Vue JS 2 Tutorial #32 - HTTP Requests using vue-resource to connect to jsonplaceholder.typicode.com. If I don't use a proxy, it triggers a CORS error. Here's my vue.config.js setup: module.exports = { devServer ...

Modify the value of Bootstrap's collapse button when it is clicked

Even after extensively searching the forum and Google, as well as reading numerous articles, I am still unable to successfully achieve what I want. My aim is to change the value of a button upon clicking it. Specifically, if the content is currently visibl ...

Update a row within an HTML table by incorporating PHP and JavaScript/jQuery, then store the changes within a database

I have a table populated with data from the database. I would like to be able to edit each row individually and save the changes back to the database. I did some research and found that this can be accomplished using JavaScript/jQuery, but I am unsure of ...

Using InvokeScript with a WPF browser application

Can someone explain why I'm encountering the error (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME)) when trying to call a javascript function in a WPF application (.Net 4)? The application hosts a browser control and utilizes local html file ...

The error message states that the property '$refs' cannot be found on the void type

Attempting to automatically focus on the next input field after typing 1 character. Encountering error: The property '$refs' does not exist on type 'void'. Here is the code snippet: setup() { const autoFocusNextInput = (event, max: ...