【问题标题】:How to return the value inside an axios get request? [duplicate]如何在 axios get 请求中返回值? [复制]
【发布时间】:2020-04-17 15:35:00
【问题描述】:

我正在做一个 Vue 项目。现在我正在通过 JWT 处理身份验证。为此,我正在创建一个模块“axios.js”,该模块应导入 main.js 以允许进行令牌验证,从而为用户授予权限。

主要思想是将令牌传递给端点/endpoint并让它返回状态码。

我目前的问题是我无法返回状态码,我得到的是 Promise 而不是布尔值。

auth.js

import axios from "axios";

var config = {
  headers: { Authorization: "Bearer " + localStorage.getItem("usertoken") }
};

export default async function isAuth() {
  let responseStatus = axios.get("http://localhost:5000/endpoint", config);

  let status = await responseStatus.then(res => {
    if (res.status == 200) {
      return true;
    } else {
      return false;
    }
  });
  return status;
}

main.js 文件的相关部分如下。剩下的就是imports和routes,这里可能不需要。

ma​​in.js

import isAuth from "./axios/auth.js";

const router = new VueRouter({
  mode: "history",
  routes
});

router.beforeEach((to, from, next) => {
  // eslint-disable-next-line no-console
  console.log(isAuth());
  var requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if (requiresAuth && !isAuth()) {
    next("/login");
  } else if (to.path == "/login" && isAuth()) {
    next("/home");
  } else {
    next();
  }
});

在下面的 main.js 中找到带有console.log(isAuth()) 的打印屏幕:

console log

如果需要更多信息,请告诉我!谢谢。

【问题讨论】:

  • 您好@TylerRoper,感谢您的快速回答!我正在尝试按照那里的建议使用.then(),但似乎我无法从isAuth() 函数返回true 或false。

标签: javascript vue.js axios es6-promise vue-router


【解决方案1】:

Axios.get 已经返回了一个 Promise,所以你可以从你的 isAuth 函数中返回 axios.get(...)。然后,在您使用 isAuth 函数的地方,您可以运行 isAuth().then(...) 或通过执行 await isAuth(); 来使用 async/await

import isAuth from './axios/auth.js'

var config = {
  headers: {
    'Authorization': "Bearer " + localStorage.getItem('usertoken')
  }
};

export default async function isAuth() {
  // Axios.get already returns a promise, so just return Axios.get
  return axios.get("http://localhost:5000/endpoint", config);
}


const router = new VueRouter({
  mode: 'history',
  routes
})


router.beforeEach((to, from, next) => {
  // eslint-disable-next-line no-console
  console.log(isAuth()) // This will just log a Promise.
  var requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  isAuth().then(result => {
    if (result) {
      // result success
    } else {
      // result fail
    }
  });
});


// Or, with async/await

router.beforeEach(async(to, from, next) => {
  // eslint-disable-next-line no-console
  console.log(isAuth()) // This will just log a Promise.
  var requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const isAuthed = await isAuth();
  if (isAuthed) {
    // result success
  } else {
    // result fail
  }
});

另外,请注意Promises 也有一个用于错误处理的.catch 函数。您可能需要添加它,以便处理端点返回的任何异常。

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2021-02-03
    • 2021-11-10
    • 1970-01-01
    • 2019-05-31
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多