【问题标题】:Axios - Cant set and get data in objectAxios - 无法在对象中设置和获取数据
【发布时间】:2018-08-20 20:24:18
【问题描述】:

我将 Axios 库用于我的 ajax 请求,因此我创建了一个 axios 实例。

当我点击端点 /user/login 时,成功响应将返回一个令牌,我将在标头中使用该令牌以供将来调用,因为 API 是安全的。

问题是当我执行console.log(authUser) 时,即使在.then() 中,我正在设置authUser.bearerToken,对象也是空的。

为什么会这样?解决方案是什么?谢谢。请参阅下面的代码。

var ax = axios.create({
    baseURL: 'http://api.site.test',
    timeout: 5000,
    headers: { 
        'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx' 
    }
});


var authUser = {};

// log the user in
ax.post('/user/login', {
    email: 'e@maiiiiiiiiil.com',
    password: 'ThisIsACoolPassword123!'
})
.then(function (response) {
    // set the bearer token
    authUser.bearerToken = response.data.token;
    ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
})
.catch(function (error) {
    console.log(error);
});

console.log(authUser);

【问题讨论】:

标签: javascript variables token axios


【解决方案1】:

这是因为它是异步的。与 /user/login 对话的代码需要一些时间,但您的代码仍在继续。

所以顺序是

  1. 创建基础 axios
  2. 将 authUser 定义为空对象
  3. 向 /user/login 发送请求
  4. Console.log authUser
  5. 从发布请求中获取响应

放3个控制台日志可以看得更清楚。

var ax = axios.create({
    baseURL: 'http://api.site.test',
    timeout: 5000,
    headers: { 
        'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx' 
    }
});


var authUser = {};
console.log('authUser is ' + authUser);

// log the user in
ax.post('/user/login', {
    email: 'e@maiiiiiiiiil.com',
    password: 'ThisIsACoolPassword123!'
})
.then(function (response) {
    // set the bearer token
    authUser.bearerToken = response.data.token;
    ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
    console.log('2. authUser is ' + authUser);
})
.catch(function (error) {
    console.log(error);
});

console.log('3. authUser is ' + authUser);

您将按以下顺序看到它:1、3、2 而不是 1、2、3。

【讨论】:

    【解决方案2】:

    ax.post 是异步的(非阻塞),因此它不会按照您希望它执行的顺序执行,即它可以随时(或同时)执行。你要么必须使用回调或async...await 来处理这个

    function f() {
    
        var ax = axios.create({
            baseURL: 'http://api.site.test',
            timeout: 5000,
            headers: { 
                'X-Api-Client-Secret': 'xxxxxxxxxxxxxxxx' 
            }
        });
    
        var authUser = {};
        var response;
    
        ; ( async () => {
    
            // log the user in
            try {
                response = await ax.post('/user/login', {
                    email: 'e@maiiiiiiiiil.com',
                    password: 'ThisIsACoolPassword123!'
                })
            } catch(ex) {
               response = ex;
            } finally {
               if ( Error[Symbol.hasInstance](response) )
                   return console.log(response);
               authUser.bearerToken = response.data.token;
               ax.defaults.headers.common['Authorization'] = authUser.bearerToken;
             }
        })(); 
        console.log(authUser)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 1970-01-01
      • 2021-06-15
      • 2021-11-20
      • 2021-05-03
      • 1970-01-01
      • 2020-01-25
      • 2021-01-31
      • 2021-03-24
      相关资源
      最近更新 更多