The login function in Nativescript Vue successfully returns a true value

Hello, I am currently using a function that is quite similar to this one with some minor tweaks here.

However, I have encountered an issue when trying to log in to my REST API. Even if I input the incorrect username or password, it still authenticates me and logs me in.

The problem lies in the fact that it should trigger the catch block when the credentials are wrong, but for some reason, it fails to do so. This was a previous issue that I managed to resolve, but now I am struggling to understand why it is happening again.

In my Login.vue file:

     login() {
            this.$backend
                .login(this.user)
                .then(() => {

                    // if login success then save login and password in local storage
                    appSettings.setString("username", this.user.username);
                    appSettings.setString("password", this.user.password);


                    this.$store.commit('setActualPage', 'Main');
                    this.processing = false;
                    this.$navigateTo(Main, { clearHistory: true });

                })
                .catch(() => {
                    this.processing = false;
                    this.alert(
                    "Username or password are not correct."
                    );
                });
        },

and in my backend-service.js file:

  login(user) {

    return httpModule.request({
        url: "MYRESTAPIURL",
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "username": user.username,
            "password": user.password,
            "apikey": "814973593645gg6db8ca6983789f"
        }
    }).then((response) => {
        let result = response.content.toJSON();


        return result;

        //console.log(result.premiumdays)
    }, (e) => {
        console.log(e);
    });
}

With the line return result;, even if the credentials are incorrect, the output shows:

{ error: 'Not connected.' }

Even adding return; to return false does not prevent the authentication process.

Answer №1

When the back-end service login fails, it sends back a result JSON to your page (login.vue). Therefore, it is advisable to include code to verify the returned JSON data:

In login.vue:


login() {
            this.$backend
                .login(this.user)
                .then((resp) => {

                   // Verify the return data
                   if(resp && resp.error){
                       // If login fails, take necessary action
                        this.processing = false;
                        this.alert(
                           "Username or password are not correct."
                        );
                   }else{
                        // If login is successful
                   }

                })
                .catch(() => {
                    this.processing = false;
                    this.alert(
                    "Username or password are not correct."
                    );
                });
        },

The catch statement will only be executed if the HTTP response code is not 200. In this case, the login failed is not an error request, but rather a successful request with error data.

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

Using AJAX to populate a dropdown menu in a CodeIgniter application

I'm having an issue with using AJAX to populate a dropdown option. Here is the JavaScript code I am using: <script type="text/javascript"> $(document).ready(function(){ $("#sepatu").click(function(e){ e.preventDefault() ...

Prevent redirection on buttons within ionic lists

THE ISSUE: I am facing an issue in my Ionic app where I am using the ion-list component. Each item in the list can be swiped to reveal a button (add/remove to favorites). Additionally, each item serves as a link to another page. The problem arises when ...

Updating the Animation for Datepicker Closure

While using the date picker, I want it to match the width of the input text box. When closing the date picker, I prefer a smooth and single motion. However, after selecting a from and to date, the datepicker no longer closes smoothly. I have attempted sol ...

Autofill Dropdown in AngularJS Using Data from Previous Page

Despite searching extensively on StackOverFlow, I was unable to find the answer I needed. So, I am posting my question below. I have a form that includes a dropdown menu. When a user clicks a button, they are taken to a new HTML page with additional infor ...

Express server unable to process Fetch POST request body

I'm currently developing a React app and I've configured a basic Express API to store user details in the database app.post("/register", jsonParser, (req, res) => { console.log("body is ", req.body); let { usern ...

tips for transferring a javascript function value to a label within a webform

Currently, I am in search of the latitude and longitude coordinates for a specific address input by the user. Upon clicking a button, the script provided below is triggered to display an alert with the latitude and longitude values: <script type="text/ ...

Enhancing jQuery Component while making an Ajax request

When a user clicks a button, I am making an ajax call to send out multiple emails. My goal is to update a "Please wait..." div before and after the call with status updates, as well as report any errors that may occur. However, I have encountered an issue ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

Is it possible to call a JavaScript file located inside a Maven dependency's jar?

In the process of developing a Spring MVC web application using Apache Tiles, I have incorporated JavaScript libraries such as JQuery by including them in the pom.xml file as dependencies. My query pertains to whether I can access these scripts from within ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

Vue/Vuex - using async dispatch for AJAX requests in multiple components

I am working with vuex and using a store module to load user lists in my app through ajax. After the list is loaded, it doesn't fetch again if it's already present in the vuex store. I have implemented this logic in the main application layout as ...

Exploring the Applications of Directives in Multiple Modules within Angular 2

When I declare the directive in two modules, I get an error that says Type PermissionDirective is part of the declarations of 2 modules. However, when I declare it in only one module, I receive an error stating Can't bind to 'isPermission' s ...

Add the bannercode snippet found on a webpage

I am currently facing an issue with appending a banner code to the end of a URL. The scenario is as follows: An individual receives an email with a link to a website (SITE1), where the URL includes a banner code, such as www.site1.com?banner=helloworld O ...

The functionality of CSS3 animations may sometimes be unreliable following the onLoad event

Here is a snippet of code to consider: $(function() { $('#item').css({ webkitTransform: 'translate(100px, 100px)' }); }); The element I am attempting to move has the following CSS properties: transform: translate3d(0 ...

Increase or decrease values in an input field using Vue3 when typing

I am looking to implement a feature where users can input numbers that will be subtracted from a fixed total of 100. However, if the user deletes the input, I want the difference to be added back to the total of 100. Despite my attempts, the subtraction wo ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

Generating a collection of items within a JavaScript object

Struggling with sending a json object to a java API backend that requires an Object containing a list of objects. Wondering if it's possible to create a list of objects inside a javascript Object. While I know we can create an "Array" of objects with ...

Issue with the string formatting in Vue.js is causing unexpected behavior

Hi there, I'm currently working on dynamically styling a div in VueJs and running into an issue with the this.currentProgressLevel not being applied to the width property within the currentStyle object. I've attached a screenshot of the code I&ap ...