An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs:

Request URL: http://localhost:25971/undefined/api/Account/Register

Request URL: http://localhost:25971/undefined/Token

The following code snippet shows the mainCtrl controller:

    (function () {
    "use strict";
    angular
        .module("userManagement")
        .controller("mainCtrl", ["userAccount", mainCtrl])

    function mainCtrl(userAccount) {
        var vm = this;
        vm.isLoggedIn = false;
        vm.message = '';
        vm.userData = {
            userName: '',
            email: '',
            password: '',
            confirmPassword: ''
        };

        vm.registerUser = function () {
            vm.userData.confirmPassword = vm.userData.password;
            userAccount.registration.registerUser(vm.userData, function (data) {
                vm.confirmPassword = "";
                vm.message = "...Registration successful";
                // vm.login();
            });
        }
        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;
            userAccount.login.loginUser(vm.userData, function (data) {
                vm.isLoggedIn = true;
                vm.password = "";
                vm.message = "";
                vm.token = data.access_token;
            });
        }
    }
}());

Below, you can find the code for the userAccount factory method:

(function () {
    "use strict";
    angular.module("common.services")
    .factory("userAccount", ["$resource", "appsettings", userAccount])
    function userAccount($resource, appsettings) {
        return {
            registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
                {
                    'registerUser': { method: 'POST' }
                }),
            login: $resource(appsettings.serverPath + "/Token", null,
                {
                    'loginUser': {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: function (data, headersGetter) {
                        var str = [];
                        for (var d in data) {
                            str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                            return str.join("&")
                        }
                    }
                }
            })
        }
    }

})();

The appsettings constant is defined as follows:

(function () {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverpath:"http://localhost:25879/"
    });
}());

If anyone familiar with Angular and WebAPI could offer help or guidance on troubleshooting this issue, it would be greatly appreciated!

Answer №1

Make sure your appConfig constant is structured like this:

(function (angular) {
   "use strict";
    angular.module("common.settings", ["ngResource"]).constant("appConfig", {
        apiUrl: "http://localhost:25879"
    });
}(angular));

Note that the property APIUrl must be capitalized correctly to match its usage later on. Check for typos and ensure consistency in casing.

Answer №2

Determine the presence of serverPath within the apiSettings object

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

Comparing Objects in an Array to Eliminate Duplicates and Make Updates in Javascript

I am working with an array of objects that is structured like this: 0: Object ConsolidatedItem_catalogId: "080808" ConsolidatedItem_catalogItem: "undefined" ConsolidatedItem_cost: "0" ConsolidatedItem_description: "Test Catalog Item" ConsolidatedItem_ima ...

Creating a JavaScript array in Rails 4 based on current data without the need to reload the webpage

Currently in my rails 4 app, I am working on a unique tags validation using jquery validate to ensure that tags are not duplicated before they can be added to an item. The tag list structure is as follows: <div id="taglist"> <span class="label ...

The Ajax POST call was unsuccessful

I seem to be encountering an issue, even though everything appears to be correct. I am currently developing on localhost and I am facing difficulties loading a file. This is the code I am using. I am working in NetBeans and the console shows no errors. & ...

Customize the default styles for Angular 2/4 Material's "md-menu" component

Seeking to customize default styles of md-menu in Angular Material. The challenge lies in the dynamic generation of elements by Angular Material, preventing direct access from HTML. Visual representation of DOM: https://i.sstatic.net/v8GE0.png Component ...

Transfer the array using Ajax to a PHP script

I have an array generated using the .push function that contains a large amount of data. What is the most effective way to send this data to a PHP script? dataString = ??? ; // Is it an array? $.ajax({ type: "POST", url: "script.php" ...

Insert image using AJAX

I am attempting to use Ajax to dynamically add an <img> element to a div on my webpage. The image's name needs to be fetched from a database. Although I have successfully added the <img> tag to the div and set the correct source (src) att ...

Shading THREE.js Color with Textures

I have added a simple box to my scene, and I am looking to create a shader that will apply a texture to it and add color to this texture. Here is my vertex shader (nothing special about it): <script id="vertexShader" type="x-shader/x-vertex"> ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

Utilizing Angular 1.4.8 and lodash to effectively parse an array of objects with conditional parameters

DEVELOPER TOOLS Angular version 1.4.8, lodash version 4.0 SOLUTION IMPLEMENTATION After building on Derek's code contribution below, I have arrived at the following solution. It was necessary to make adjustments as using _.property() or _.map() ch ...

The URL in an AJAX request includes a repeating fragment due to a variable being passed within it

const templatePath = envVars.rootTemplateFolder + $(this).attr('link'); console.log("templatePath : ", templatePath); $.ajax({ method: "GET", url: templatePath, context: this, success : function(result){ ...

Exploring the wonders of Vue.js and Laravel's type casting techniques

I have implemented DB2-style IDs for my database records in my Laravel 5.7 application, like this example: 201402241121000000000000. When trying to use it in my Vue component, I used the following syntax: <mycomponent v-bind:listing-key="{{ $listing-&g ...

Verify the form data before triggering the ajax call with just one click

Ensuring that all required areas are completed in a form is crucial. The form needs to be validated properly to either reject the request with a message showing what information is missing, or submit it successfully... The rejection process works well as ...

Find the specific element that is visible within a customized viewport, such as a div or ul

Exploring the capabilities of the Viewport Selectors for jQuery plugin, here is a snippet of its source code: (function($) { $.belowthefold = function(element, settings) { var fold = $(window).height() + $(window).scrollTop(); return fold <= $ ...

What is causing this error to appear in Next.js? The <link rel=preload> is showing an invalid value for `imagesrcset`

I've got a carousel displaying images: <Image src={`http://ticket-t01.s3.eu-central-1.amazonaws.com/${props[organizationId].events[programId].imgId}_0.cover.jpg`} className={styles.carouselImage} layout="responsive" width={865} ...

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

What is the purpose of utilizing these three JavaScript function parameters?

I've been researching JavaScript functions and arguments, but I haven't found anything that fully explains a function like the one below. For reference, you can check out the original tutorial. In createPuppy, there are three arguments: req, res ...

What are some solutions for resolving the npm error code elifecycle issue?

After following the documentation, I successfully installed React JS but encountered an error when trying to run the app. The error code displayed was elifecycle npm err errno 1. Can someone please assist me in resolving this issue? Additionally, it's ...

Retrieving the path parameter in a Next.js APIabstractmethod

I need assistance with extracting information from the file routes/api/[slug]/[uid].ts Specifically, I am looking to retrieve the slug and uid within my handler function. Can anyone provide guidance on how to achieve this? ...