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('/')
})
},