首页 > 解决方案 > Vue.js 通过 Axios 使用 API 给出错误:未捕获(承诺中)TypeError:无法读取未定义的属性“协议”

问题描述

我尝试在 VueJS 中通过 Axios 使用 api。但是当我尝试获取数据时它会出错。控制台日志(res.data)。需要你的帮助。看起来我错过了什么

未捕获(承诺中)类型错误:无法读取未定义的属性“协议”

这是 API.Js 中的代码

import axios from 'axios';
import API from '../API';



var urlLogin = API.url.host + '/login';

var login = {
    init: function(){
        this.vueConfig();
        if(localStorage.getItem('token') != null){
            window.location.replace("./input-mobile.html");
        }
    },
    vueConfig: function(){
        var app = new Vue({
            el: '#app',
            data: {
                isSubmit: false,
                email: "email",
                password: "password",
            },
            methods: {
                submitLogin: function(){
                    this.isSubmit = true;
                    axios.post()
                    axios({
                        method: 'post',
                        url: urlLogin,
                        data: {
                            email: this.email,
                            password: this.password
                        }
                    }).then(res =>{
                        console.log(res.data);
                        this.isSubmit = false;
                        localStorage.setItem("token", res.data.access_token);
                        localStorage.setItem("name", res.data.fullname);
                        window.location.replace("./input-mobile.html");
                    }, err =>{
                        console.log(err);
                        this.isSubmit = false;
                    });
                }
            }
        });
    }
}

module.exports = login;

API 没问题。在浏览器 api 的网络(检查)中给出正确的响应。但它无法获取数据

标签: javascriptvue.jsaxios

解决方案


您在 Axios 回调中引用了错误的对象。尝试let self = this在方法的开头添加submit,然后在回调中更改this.isSubmit.self.isSubmit

submitLogin: function(){
  let self = this;
  this.isSubmit = true;
  axios.post()
  axios({
     method: 'post',
     url: urlLogin,
     data: {
         email: this.email,
         password: this.password
     }
  }).then(res =>{
     console.log(res.data);
     self.isSubmit = false;
     localStorage.setItem("token", res.data.access_token);
     localStorage.setItem("name", res.data.fullname);
     window.location.replace("./input-mobile.html");
  }, err =>{
     console.log(err);
     self.isSubmit = false;
  });
}

推荐阅读