The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method.

The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of undefined.

var AuthClient = (function () {
    function AuthClient($http, baseUrl) {
        this.baseUrl = undefined;
        this.http = null;
        this.jsonParseReviver = undefined;
        this.http = $http;
        this.baseUrl = baseUrl !== undefined ? baseUrl : "";
    };
    AuthClient.prototype.login = function (auth) {
        var _this = this;
        var url_ = this.baseUrl + "/api/v1/auth/login";
        var content_ = JSON.stringify(auth ? auth.toJS() : null);
        return this.http({
            url: url_,
            method: "POST",
            data: content_,
            transformResponse: [],
            headers: {
                "Content-Type": "application/json; charset=UTF-8",
                "Accept": "application/json; charset=UTF-8"
            }
        }).then(function (response) {
            return _this.processLogin(response);
        }, function (response) {
            if (response.status)
                return _this.processLogin(response);
            throw response;
        });
    };
...}());
exports.AuthClient = AuthClient;

My angular code includes:

    var client = AuthClient('http://localhost:14959/');
    var call = client.prototype.login(data);

After debugging the application, I noticed that it enters the function AuthClient. I even attempted to change it to this, but the issue persists:

function AuthClient($http, baseUrl) {
    this.baseUrl = baseUrl;
};

Another error that I am encountering is:

Uncaught ReferenceError: exports is not defined
. I am unsure if this is related to the current issue or not, but thought it was worth mentioning.

Error trace:

TypeError: Cannot set property 'baseUrl' of undefined
    at AuthClient (RenterLogApiBackendClient.js:19)
    at b.$scope.login (HomeController.js:16)
    at fn (eval at compile (angular.min.js:1), <anonymous>:4:206)
    at b (angular.js:16123)
    at e (angular.js:26490)
    at b.$eval (angular.js:17913)
    at b.$apply (angular.js:18013)
    at HTMLFormElement.<anonymous> (angular.js:26495)
    at HTMLFormElement.dispatch (jquery-3.1.1.min.js:3)
    at HTMLFormElement.q.handle (jquery-3.1.1.min.js:3)

Answer №1

To properly initiate your AuthClient function, make sure to return the constructor inside the function and then call it using the new keyword:

var AuthClient = (function () {
    // ...

    return AuthClient;
}());

var client = new AuthClient('http://localhost:14959/');

You may not need the exports line in this scenario.

Answer №2

This line is unnecessary:

this.baseUrl = undefined;

If you encounter this scenario again:

this.baseUrl = baseUrl !== undefined ? baseUrl : "";

A more efficient approach to achieve the same result is:

this.baseUrl = '' || this.baseUrl;

In the AuthClient class, there are two parameters, with the second one being baseUrl. However, when assigning a value to it, only one parameter is provided.

To address this, create another function within the class and use the parameter accordingly.

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

"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship: // Branch entity @ManyToMany( (type) => User, (e) => e.branches ) users: User[]; // User entity @ManyToMany( (type) => Branch, (e) ...

Issue with Jquery animation

I'm facing a strange issue. I've created a jQuery function that animates the result bars of a poll. function displayResults() { $(".q_answers1 div").each(function(){ var percentage = $(this).next().text(); $(this).css({widt ...

Enhancing Numbers with JavaScript

What I'm Looking for: I have 5 counters on my webpage, each starting at 0 and counting upwards to different set values at varying speeds. For example, if I input the values of 10, 25, 1500, 400, and 500 in my variables, I want all counters to reach t ...

Flowplayer playlist stops after playing the first clip

I am having issues with my flowplayer configuration, as it is not behaving as I expected. After the first video ends, I want the second and subsequent videos to play automatically. Can anyone provide some guidance on how to achieve this? $f("player", "/fl ...

Display all keys and values in a dynamically populated object on my screen - React

I have a dynamic object with nested objects, and I want to display every key and value. Even if there are objects within the main object, I need to show their keys and values as well. Here is an example of the object: info:{ address:{ city: {__o ...

Attempting to sort through elements in JavaScript

I'm looking to filter specific films based on choices made in the dropdown menus below. <select id="filmDropdown"> <option value="0">All Films</option> <option value="1">Film 1</option> <option ...

The UTF-8 data sent by JQuery AJAX is not being correctly processed by my server, but only in Internet Explorer

When I send UTF-8 Japanese text to my server, it works fine in Firefox. Here are the details from my access.log and headers: /ajax/?q=%E6%BC%A2%E5%AD%97 Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Content-Type application/x-www-form-urlencoded; char ...

Is it possible for the binding model of Mat-Checkbox to be optional or null?

Greetings everyone! I am a newcomer to the world of Angular, where I have successfully created a dynamic list of checkboxes. However, I have encountered a challenge when trying to bind selected values from an API to these checkboxes. <div *ngFor="let b ...

Mongoose JS is unable to display the query value in the output

Is there a way to use mongoose js to create a collection of kittens with specific attributes like {name: "mike"}? Once this document is created, I need to be able to view its value. I've attempted to write the following code: However, I've enco ...

performing a request to Axios API with the inclusion of ${item} within the URL

I am having trouble with calling axios in Vuetify due to backticks and ${} within the URL. I believe I need to convert it into JSON format, but my attempts have been unsuccessful. Could you please provide an explanation? Here is the code snippet. Whenever ...

I am exploring directories on my server but encountered a restriction while using $.ajax

I am currently working on designing a basic webpage using p5.js, where I have implemented a script to search for images within folders and display them all on a single page. To facilitate this process, I am utilizing the $.ajax({}); function to check ...

Choose autocomplete feature from an external source within the context of AngularJS

I am currently working on an autocomplete textbox and I stumbled upon this script that I found through my search efforts. .controller('autoCompleteCTRL', function($scope, $rootScope){ $rootScope.searchItems = [ "ActionScript", ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

What is the best way to deduct pixels from numbers using JavaScript?

Currently, I am attempting to adjust the height of the footer based on the height of another div element. My approach involves utilizing the .css("height") function. However, I am encountering difficulty as the function does not seem to return the value i ...

Update to react version 18.2.0, router-dom v6, and mui 5 for improved performance

Struggling to convert the following file or code into React's latest version and react-router-dom v6. I attempted it myself but encountered errors related to createBrowserHistory that I couldn't comprehend. My routes are stored in a JSON file and ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

Creating a personalized input slider: A step-by-step guide

I have a question about how to design a custom input slider with the label inside the field itself. The desired output should look like the screenshot below: https://i.sstatic.net/gE6EJ.png I have successfully created the input field part, but I am stru ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Is it unorthodox to utilize constructor instances as prototypes in "WebGL - Up and Running"?

In the book "WebGL - Up and Running," a unique custom geometry is created in a rather straightforward manner. However, what caught my attention was the penultimate line of code. Here's how it looked: Saturn.Rings = function ( innerRadius, outerRadius ...

I am looking to send an ajax request from the themes directory's loyalty.tpl file to the LoyaltyModule.php file in PrestaShop version 1.6.1.5

How can I successfully send an ajax request from the theme file folder/loyalty.tpl to /public_html/test/modules/loyalty/LoyaltyModule.php in Prestashop 1.6.1.5? <input id="Gcash_id" name="Gcash_id" type="text" class="form-control grey" placeholder="Ent ...