9

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

Nitish Kumar
  • 6,054
  • 21
  • 82
  • 148
  • 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 Mar 19 '19 at 03:32
  • @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 Mar 19 '19 at 03:42
  • Whatever you posted should actually work. This may be helpful https://www.nativescript.org/blog/make-http-requests-to-remote-web-services-in-a-nativescript-vue-app – Narendra Mar 19 '19 at 06:17
  • @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 Mar 20 '19 at 06:17
  • is it possible for you create playground? – Narendra Mar 20 '19 at 06:31
  • or a github may be? – Narendra Mar 20 '19 at 06:31
  • @NarendraMongiya You can find it here! https://github.com/nitish1986/sample_mobile_app – Nitish Kumar Mar 20 '19 at 06:38
  • @NitishKumar Assuming this backend is running locally, are you sure that the device you are testing on can actually reach it? – Dexter Mar 22 '19 at 15:31
  • @NitishKumar Are you sure you're using Axios correctly? I usually have to pass some `{ withCredentials: true }` kind of option to make it work with authentication? And you probably don't need your object `authHeader` – Andria Mar 23 '19 at 05:57
  • @Dexter Yes it is working fine that is why I've shared https://i.stack.imgur.com/IPJhf.png this last image – Nitish Kumar Mar 23 '19 at 07:29
  • @ChrisBrownie55 Yes, I don't think that is the problem. – Nitish Kumar Mar 23 '19 at 07:29

2 Answers2

7

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.

Manoj
  • 21,753
  • 3
  • 20
  • 41
  • I think there must be some more configuration in AndroidManifest.xml but still you gave me an idea about it. Thanks a lot!!! – Nitish Kumar Mar 25 '19 at 18:59
2

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"
belvederef
  • 2,195
  • 19
  • 16