如何在 Nativescript 应用程序中调用 axios/api [英] How to call axios/api call in Nativescript application

查看:17
本文介绍了如何在 Nativescript 应用程序中调用 axios/api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的 settings.js 文件包含.

export const authHeader = {'接受':'应用程序/json','内容类型':'应用程序/json'}

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

const postData = {grant_type: '密码',用户名:user.email,密码:user.password,客户端 ID:客户端 ID,client_secret:clientSecret,范围: '',提供者:提供者}const authUser = {}axios.post(authUrl, postData, {headers: authHeader}).then(response => {console.log('在 oauth/token url 里面')如果(响应.状态 === 200){console.log('收到回复')}}).catch((错误) => {if(err.response.status === 401){拒绝('验证错误')}别的拒绝('出了点问题')})

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

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

如您所见,我的应用程序中有 console.log 显示:

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

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

同样我使用了 nativescript's 自己的 http

和:

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

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

解决方案

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

如果您使用的是 Android 9 或更高版本,它可能会失败,因为您尚未在 AndroidManifest.xmlapplication 标记上启用 useCleartextTraffic>.

<应用程序机器人:使用CleartextTraffic =真"android:name="com.tns.NativeScriptApplication"

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

NSAppTransportSecurity<字典><key>NSAllowsArbitraryLoads</key><真/></dict>

如果您只想允许特定域,请使用 NSExceptionDomains 键并列出端点.

I'm trying to build a small application on Nativescript-vue where I'm having backend laravel framework for api calls which needs to be called to get relevant data. For example if user wants to login he needs to validate its credentials through api oauth/token so I'm trying to call this through axios here is my code:

My settings.js file contains.

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

this is being imported inside my axios calls:

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')
})

when I try to build with command tns debug android --bundle I get chrome-devtools which shows me:

Digging more deep into it I can see headers are being passed but those are only provisional:

As you can see I've console.log inside my application which show me:

Even while compiling I get following errors:

Guide me how can I achieve this. Thanks.

Edit:

Similarly I used nativescript's own http documentation something like this:

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')
});

I'm getting the same result, moreover I tried api from server end ex http://confidenceeducare.com/oauth/token it happens to be same. Normal Vue application calls the api perfectly fine. I guess there is some problem with the nativescript application. Do I need to import something more? I'm stuck with it.

If anybody is thinking my api end point is broken, I tried using the urls mentioned in example i.e. https://httpbin.org/post:

and:

When I checked my api in postman it is working over there, I'm getting at least a response with status code:

Edit 2: For reference github repository https://github.com/nitish1986/sample_mobile_app

解决方案

I tested the exact same project you have shared in Github with Android 8.0, it works perfectly fine. The axios call hits the error block as the response status (error.response.status) is 401 and data (error.response.data) returns the exact same response you see from Postman.

If you are using Android 9 or later it might fail as you haven't enabled useCleartextTraffic on your application tag in the AndroidManifest.xml.

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

With iOS also it would fail as you haven't enabled app transport security. Just to allow all Http communication within your app, you have to add the following key to your info.plist

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

In case if you want to allow only specific domains, then use NSExceptionDomains key and list the endpoints.

这篇关于如何在 Nativescript 应用程序中调用 axios/api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆