首页 > 解决方案 > 如何在 Nativescript 应用程序中调用 axios/api 调用

问题描述

我正在尝试Nativescript-vue在我拥有laravel用于​​ api 调用的后端框架的地方构建一个小型应用程序,需要调用该框架来获取相关数据。例如,如果用户想要登录,他需要通过 api 验证其凭据,oauth/token所以我试图通过以下方式调用它axios是我的代码:

我的settings.js文件包含。

export const authHeader = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

这是在我的 axios 调用中导入的:

const postData = {
    grant_type: 'password',
    username: user.email,
    password: user.password,
    client_id: clientId,
    client_secret: clientSecret,
    scope: '',
    provider: provider
}
const authUser = {}
axios.post(authUrl, postData, {headers: authHeader}).then(response => {
    console.log('Inside oauth/token url')
    if(response.status === 200)
    {
        console.log('response received')
    }
})
.catch((err) => {
    if(err.response.status === 401){
       reject('Validation error')
    }
    else
       reject('Something went wrong')
})

当我尝试使用命令构建时,tns debug android --bundle我得到chrome-devtools了显示:

api被调用

更深入地研究它,我可以看到标题正在被传递,但这些只是临时的:

标题

如您所见,我console.log在我的应用程序中向我展示了:

控制台日志

即使在编译时,我也会收到以下错误:

编译错误

指导我如何实现这一目标。谢谢。

编辑:

同样,我使用了nativescript's自己的http 文档,如下所示:

const httpModule = require("http");

httpModule.request({
    url: "http://iguru.local/oauth/token",
    method: "POST",
    headers: { "Content-Type": "application/json" },
    content: JSON.stringify({
        grant_type: 'password',
        username: this.user.email,
        password: this.user.password,
        client_id: 'check',
        client_secret: 'check',
        scope: '',
        provider: 'check'
    })
}).then((response) => {
    // Argument (response) is HttpResponse
    console.log('Action called')
    if(response.status === 200)
    {
        console.log('Response recieved')
    }
}, (e) => {
    console.log('Something went wrong')
});

我得到了相同的结果,而且我从服务器端尝试了 api,例如http://confidenceeducare.com/oauth/token它恰好是相同的。正常Vue的应用程序调用 api 非常好。我猜这个应用程序有问题nativescript。我需要导入更多的东西吗?我坚持下去。

如果有人认为我的 api 端点已损坏,我尝试使用示例中提到的 url,即https://httpbin.org/post

http

和:

在此处输入图像描述

当我检查我的 api 在postman那里工作时,我至少收到一个带有状态码的响应:

邮递员回应

编辑 2: 供参考 github 存储库https://github.com/nitish1986/sample_mobile_app

标签: javascriptvue.jsaxiosnativescriptnativescript-vue

解决方案


我使用 Android 8.0 测试了您在 Github 中共享的完全相同的项目,它运行良好。axios 调用命中错误块,因为响应状态 ( error.response.status) 为 401,并且数据 ( error.response.data) 返回与您从 Postman 看到的完全相同的响应。

useCleartextTraffic如果您使用的是 Android 9 或更高版本,它可能会失败,因为您尚未applicationAndroidManifest.xml.

<application 
        android:usesCleartextTraffic="true"
        android:name="com.tns.NativeScriptApplication"

使用 iOS 也会失败,因为您没有启用应用程序传输安全性。只是为了允许您的应用程序中的所有 Http 通信,您必须将以下密钥添加到您的info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

如果您只想允许特定域,请使用NSExceptionDomainskey 并列出端点。


推荐阅读