Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从axios中的401错误捕获调用vue中的方法?_Javascript_Authentication_Vue.js_Axios - Fatal编程技术网

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';
})