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

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

问题描述

我正在尝试在Nativescript-vue上构建一个小型应用程序,在该应用程序中我有用于调用api的后端laravel框架,需要调用该框架才能获取相关数据.例如,如果用户要登录,则需要通过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显示给我:

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

如您所见,我在应用程序内显示了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')
});

我得到了相同的结果,而且我从服务器端ex http://confidenceeducare.com/尝试了api oauth/token 它恰好是相同的.普通的Vue应用程序可以很好地调用api.我想nativescript应用程序存在一些问题.我还需要导入更多内容吗?我坚持下去.

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

和:

当我在postman中检查我的api时,它在那儿工作,我至少收到一条状态码为响应的信息:

修改2: 供参考,github存储库 https://github.com/nitish1986/sample_mobile_app

解决方案

我测试了与Android 8.0在Github中共享的完全相同的项目,它运行良好.由于响应状态(error.response.status)为401,数据(error.response.data)返回与Postman完全相同的响应,因此axios调用会击中错误块.

如果您使用的是Android 9或更高版本,则可能会由于未在AndroidManifest.xml中的application标记上启用useCleartextTraffic而失败.

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

在iOS上,由于您尚未启用应用程序传输安全性,因此也会失败.只是为了允许您的应用程序中的所有Http通信,您必须在info.plist

中添加以下密钥

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</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天全站免登陆