首页 > 解决方案 > Axios 无法从 NativeScript 中的 API 获取数据

问题描述

我用 Laravel 创建了一个本地 API。我尝试使用 Postman 运行这个返回数据的 API,但是当我在 NativesScript Javascript 文件中使用 Axios 时,它既不返回数据也不返回错误消息。

我已经尝试在函数中使用 Async 和 Await ,但仍然没有返回任何内容。

import axios from 'axios'

export default class Service {
  async testing(){
    await axios.get('https://app.app/api/testing')
        .then(res => {
           console.log(res.data);
        })
        .catch(function(error) {
           console.log(error);
        });
  }
}

我希望输出为 1,但它带有“”,我发现它永远不会进入 API(我已经放置了调试点,它没有触发器。),但邮递员工作得很好(相同的 url),它触发调试点,它确实返回值 1。

谢谢你。

标签: javascriptapiaxiosnativescript

解决方案


async/await 应该包含在 try/catch 块中。

try {
    const result = await axios.get('https://app.app/api/testing');
    console.log(result)
} catch(err) {
    console.log(err);
}

推荐阅读