Javascript 如何从axios中的401错误捕获调用vue中的方法?
我尝试的代码是这样的Javascript 如何从axios中的401错误捕获调用vue中的方法?,javascript,authentication,vue.js,axios,Javascript,Authentication,Vue.js,Axios,我尝试的代码是这样的 axios({ method:'get', url:'/user', baseURL:'https://api.github.com', auth:{ username:'username', password:'password' }
axios({
method:'get',
url:'/user',
baseURL:'https://api.github.com',
auth:{
username:'username',
password:'password'
}
}).then((response)=>{
this.errorMessage='';
console.log(response);
}).catch(function(error){
this.errorMessage='Authentication failed';
})
但我不断收到错误“Uncaught(in promise)TypeError:无法设置未定义的属性'errorMessage'”
现在通常的嫌疑犯已经被侦破了errorMessage“是在数据上声明的,并给定了值“”,因此不是这样。而响应部分的'this.errorMessage'是有效的(我测试它说'auth successful'),而捕获错误部分的'this.errorMessage'则不起作用。
context
当您使用function
关键字时,函数内部会发生变化。使用箭头函数使错误处理程序中的上下文与父作用域相同。你在你的处理器上使用它,这就是为什么它在那里工作
.catch((error)=>{
this.errorMessage='Authentication failed';
})
context
当您使用function
关键字时,函数内部会发生变化。使用箭头函数使错误处理程序中的上下文与父作用域相同。你在你的处理器上使用它,这就是为什么它在那里工作
.catch((error)=>{
this.errorMessage='Authentication failed';
})