9
votes

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 being called

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

headers

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

console.log

Even while compiling I get following errors:

compiling error

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:

http

and:

enter image description here

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

postman response

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

2
Based on most of what you printed, and looking really quickly at Axios; it won't work on NativeScript -- it is designed for Node. Anything that pulls node specific libraries doesn't work on NativeScript. Now as to your edit; that code should actually work; what error are you seeing from using the nativescript http code?Nathanael
@Nathanael I'm not getting any errors, it is just waiting for response, even in command prompt it just wait for the response and I don't know why this is showing as document in chrome console in-spite of being a XHR request.Nitish Kumar
Whatever you posted should actually work. This may be helpful nativescript.org/blog/…Narendra
@NarendraMongiya That is what it is bothering me more, wherever I've researched it says your code is fine and it should work.Nitish Kumar
is it possible for you create playground?Narendra

2 Answers

7
votes

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.

2
votes

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"