简体   繁体   中英

How to call axios/api call in Nativescript application

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:

api 被调用

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 ie https://httpbin.org/post :

http

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.

The problem has to do with how axios is imported. Try:

import axios from 'axios/dist/axios'

this also solves the Module not found: Error: Can't resolve 'net' in... error.

When importing the package normally my requests failed, returning the error

Error in v-on handler (Promise/async): "Error: Request failed with status code null"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM