Guide to making axios/api calls in a Nativescript mobile application

In my development process, I am working on creating a small application using Nativescript-vue. This application requires backend functionality that is built on the laravel framework for making API calls to retrieve relevant data. For example, when a user wants to login, their credentials need to be validated through an API call to oauth/token using axios. Below is a snippet of the code:

The settings.js file contains the following:

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

This is then imported and used within 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')
})

During the build process with the command tns debug android --bundle, I encounter the chrome-devtools showing issues related to headers being only provisional:

I have added some console.log statements in the application which reveal:

Further inspection also shows various errors during compilation:

If anyone has insights on how to resolve this issue, it would be greatly appreciated. Thank you.

Edit:

Additionally, I attempted to use Nativescript's built-in http module by referring to the official documentation:

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 received')
    }
}, (e) => {
    console.log('Something went wrong')
});

Despite trying different endpoints like , the results remain consistent. Strangely, Vue applications seem to handle these API calls without any issues. Could there be additional dependencies or configurations needed in Nativescript? Your help is much appreciated as I am currently stuck.

For verification purposes, I tested the APIs using URLs from examples such as https://httpbin.org/post:

and:

When testing in postman, I did receive responses along with status codes:

Edit 2: To access the GitHub repository for reference, visit https://github.com/nitish1986/sample_mobile_app

Answer №1

After testing the project you shared on Github using Android 8.0, I found that it works flawlessly. When making the axios call, it enters the error block due to a 401 response status (error.response.status) and returns the same data (error.response.data) as seen in Postman.

If you are using Android 9 or later, it may fail if you haven't enabled useCleartextTraffic in your application tag within the AndroidManifest.xml.

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

Similarly, with iOS, it will also fail unless you enable app transport security. To allow all HTTP communication within your app, add the following key to your info.plist:

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

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

Answer №2

The issue arises from the way axios is imported. Consider using the following method:

import axios from 'axios/dist/axios'

This approach also resolves the

Module not found: Error: Can't resolve 'net' in...
error.

After trying to import the package in the usual manner, my requests were unsuccessful and resulted in the following error message:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to Access Browser Page

After printing out the URL in the console, I encountered an issue while trying to retrieve it using browser.get(). The error message displayed is as follows: Failed: Parameter 'url' must be a string, not object. Failed: Parameter 'url&apo ...

Java servlet is unable to interpret the name of an html select tag

Currently, I am implementing a feature where table rows with select boxes are added dynamically and the values of these select boxes are retrieved in a servlet. The process of adding the select boxes is functioning properly; however, when attempting to ret ...

Mongoose throws a "Possibly unhandled rejection" error when trying to use ContactList.insert as it is not a recognized function

Currently working on a small project using the MEAN stack, but encountering an issue with sending a post request where console.log displays an error. https://i.sstatic.net/7nUXH.jpg Error Message: Possibly unhandled rejection: {"data":"TypeError: Contac ...

Dealing with CORS policy or 404 errors when using Vue.js and socket.io in conjunction with the npm run serve command

I'm currently working on developing my project locally. Running on my local machine is a simple socket.io server: const io = require('socket.io')(); io.listen(3000); In my Vue.js application, I aim to establish a connection with a socket ...

What could be causing the slowdown of my Heroku web app compared to Flask running on localhost?

Currently, I am creating a simple web application that incorporates Vue, Flask, and SQLite. The application runs smoothly on localhost with most of the data processing being handled by pandas. Upon reviewing the localhost logs, it is evident that the dat ...

Ways to verify when leaving the webpage

After spending an excessive amount of time searching for this information, I finally figured it out. So here you have it, I'm sharing the steps to create a custom "ARE YOU SURE YOU WANT TO LEAVE THIS PAGE?" dialog. ...

A guide to effectively unit testing a Vue composition in isolation

In my project, I have organized my code in a similar way to the example in the documentation. This involves keeping my composition logic in a separate file from the component itself. Here is an overview of how it looks: // composition.js import { onMounte ...

Is there a workaround for the issue of the NodeJS Web Cryptography API require() being undefined in an unsecure origin (Heroku App)?

My goal is to implement the experimental Web cryptography API (SubtleCrypto) on my Node.js server hosted on Herokuapp. The aim is to encrypt data from a fetch request sent from gitpages to herokuapp, concealing sensitive information from the browser consol ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

Error TS2322: The function signature '(state: State, exRep: number, exName: string) => void' does not match the expected type 'Mutation' in Vuex when using TypeScript

I'm currently facing an issue while working with Vuex and TypeScript. I have encountered the following error in my code, but I am unsure how to resolve it: The error : TS2322: Type '(state: State, exRep: number, exName: string) => void' i ...

Is it recommended to use async callback as a best practice?

Until now, I have always called async callbacks without returning them. Unfortunately, I recently discovered that the code following the callback call also gets executed. What a realization! Let me illustrate with an example: var asyncFunctionNoReturn = ...

Implementing fetch within a custom hook to display a loader within a return function

customFetch hook: import React, { useState, useEffect } from 'react'; const customFetch = (url, options) => { const [response, setResponse] = useState(null); const [error, setError] = useState(null); useEffect(() => { (async () ...

Utilizing Flask to gather information from a leaflet map

I am currently working on creating a webpage using Flask. The webpage features a leaflet map where users can click to create a marker that opens a popup window with a link. The link's purpose is to open a new page displaying the longitude and latitude ...

Display the header.vue component in Nuxt with data fetched from the store

My header.vue file contains user information retrieved from the store (vuex), such as username and profile image. Everything functions properly when navigating through the website by clicking on links. However, when the page is reloaded, the header with ...

Hiding or removing DOM elements with ng-bootstrap pagination

I am in the process of incorporating pagination into my project using ng-bootstrap pagination. In my HTML, I am combining an ngFor loop with the slice pipe to filter elements for display. <tr *ngFor="let bankAccount of bankingAccounts | slice: (p ...

Creating getter and setter functions for an input field model property in Angular

I need help creating getter and setter methods for an input field property. Here is my attempted code: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', st ...

Passing data from React component to JavaScript page or function

I am trying to pass a variable called "pokemon" from Cell.js to Detail.js. Cell.js creates buttons, each representing a different pokemon. When clicked, it should navigate to a detailed page about the specific pokemon. Therefore, I need to send the pokemo ...

JQuery does not recognize $(this) after the HTML has been altered

I manage a website that includes several href links and 2 buttons that have the ability to modify those links dynamically. <div class="links"> <p class="hlCategory">Classical Mechanics</p> <ul> <li><a cl ...

Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class= ...

Refresh list items automatically after deletion in Vue.js

Issue Currently, I have a view that displays a list of items and allows for the deletion of individual items. The delete functionality is working as expected - upon manual page refresh, the deleted item disappears. However, the problem arises when the ite ...