Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating

Failed to load resource: net::ERR_CONNECTION_REFUSED
. Typically, I would resolve such issues through Googling, however, due to the novelty of these technologies for me, I am feeling quite lost.

Everything progressed smoothly until I reached the "register" step towards the end of the tutorial, where the aforementioned error surfaced. Could someone verify the tutorial to check if the registration process works correctly? Alternatively, please let me know if any components used in the tutorial are outdated or malfunctioning. As previously stated, the tutorial can be completed in under 10 minutes.

Provided below is the code snippet:

AngularJSClient Solution

app.js

(function () {
    'use strict';
    // Module name is handy for logging
    var id = 'app';
    // Create the module and define its dependencies.
    var app = angular.module('app', [
    ]);
    app.config(['$httpProvider', function ($httpProvider) {
        // Use x-www-form-urlencoded Content-Type
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        // Override $http service's default transformRequest
        $httpProvider.defaults.transformRequest = [function (data) {
            /**
             * The workhorse; converts an object to x-www-form-urlencoded serialization.
             * @param {Object} obj
             * @return {String}
             */
            var param = function (obj) {
                var query = '';
                var name, value, fullSubName, subName, subValue, innerObj, i;
                for (name in obj) {
                    value = obj[name];
                    if (value instanceof Array) {
                        for (i = 0; i < value.length; ++i) {
                            subValue = value[i];
                            fullSubName = name + '[' + i + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if (value instanceof Object) {
                        for (subName in value) {
                            subValue = value[subName];
                            fullSubName = name + '[' + subName + ']';
                            innerObj = {};
                            innerObj[fullSubName] = subValue;
                            query += param(innerObj) + '&';
                        }
                    }
                    else if (value !== undefined && value !== null) {
                        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                    }
                }
                return query.length ? query.substr(0, query.length - 1) : query;
            };
            return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
        }];
    }]);
    // Execute bootstrapping code and any dependencies.
    app.run(['$q', '$rootScope',
        function ($q, $rootScope) {
        }]);
})();

mainCtrl.js

(function () {
    'use strict';
    var controllerId = 'mainCtrl';
    angular.module('app').controller(controllerId,
        ['userAccountService', mainCtrl]);
    function mainCtrl(userAccountService) {
        // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
        var vm = this;
        // Bindable properties and functions are placed on vm.
        vm.title = 'mainCtrl';
        vm.isRegistered = false;
        vm.isLoggedIn = false;
        vm.userData = {
            userName: "",
            password: "",
            confirmPassword: "",
        };
        vm.registerUser = registerUser;
        vm.loginUser = loginUser;
        vm.getValues = getValues;
        function registerUser() {
            userAccountService.registerUser(vm.userData).then(function (data) {
                vm.isRegistered = true;
            }, function (error, status) {
                vm.isRegistered = false;
                console.log(status);
            });
        }
        function loginUser() {
            userAccountService.loginUser(vm.userData).then(function (data) {
                vm.isLoggedIn = true;
                vm.userName = data.userName;
                vm.bearerToken = data.access_token;
            }, function (error, status) {
                vm.isLoggedIn = false;
                console.log(status);
            });
        }
        function getValues() {
            userAccountService.getValues().then(function (data) {
                vm.values = data;
                console.log('back... with success');
            });
        }
    }
})();

userAccountService.js

(function () {
    'use strict';
    var serviceId = 'userAccountService';
    angular.module('app').factory(serviceId, ['$http', '$q', userAccountService]);
    function userAccountService($http, $q) {
        // Define the functions and properties to reveal.
        var service = {
            registerUser: registerUser,
            loginUser: loginUser,
            getValues: getValues,
        };
        var serverBaseUrl = "http://localhost:60737";

        return service;
        var accessToken = "";
        function registerUser(userData) {
            var accountUrl = serverBaseUrl + "/api/Account/Register";
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: accountUrl,
                data: userData,
            }).success(function (data, status, headers, cfg) {
                console.log(data);
                deferred.resolve(data);
            }).error(function (err, status) {
                console.log(err);
                deferred.reject(status);
            });
            return deferred.promise;
        }
        function loginUser(userData) {
            var tokenUrl = serverBaseUrl + "/Token";
            if (!userData.grant_type) {
                userData.grant_type = "password";
            }
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: tokenUrl,
                data: userData,
            }).success(function (data, status, headers, cfg) {
                // save the access_token as this is required for each API call. 
                accessToken = data.access_token;
                // check the log screen to know currently back from the server when a user log in successfully.
                console.log(data);
                deferred.resolve(data);
            }).error(function (err, status) {
                console.log(err);
                deferred.reject(status);
            });
            return deferred.promise;
        }
        function getValues() {
            var url = serverBaseUrl + "/api/values/";
            var deferred = $q.defer();
            $http({
                method: 'GET',
                url: url,
                headers: getHeaders(),
            }).success(function (data, status, headers, cfg) {
                console.log(data);
                deferred.resolve(data);
            }).error(function (err, status) {
                console.log(err);
                deferred.reject(status);
            });
            return deferred.promise;
        }
        // include the Bearer token with each call to the Web API controllers. 
        function getHeaders() {
            if (accessToken) {
                return { "Authorization": "Bearer " + accessToken };
            }
        }
    }
})();

WebAPI2 Solution

WebApiConfig.cs*

public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    //Enable CORS for all origins, all headers, and all methods,
    // You can customize this to match your requirements
    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

}

The issue persists while attempting to test the Register function during the tutorial. An error message reading

Failed to load resource: net::ERR_CONNECTION_REFUSED
keeps appearing.

Answer №1

  1. Install the Microsoft.AspNet.WebApi.Cors package using the command "Install-Package Microsoft.AspNet.WebApi.Cors"
  2. In your WebApiConfig file, add config.EnableCors() as shown below:

    public static void Register(HttpConfiguration config)
    {
        //Cors code
        config.EnableCors();
    
        config.MapHttpAttributeRoutes();
    
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    
  3. Finally, in the ConfigureAuth method, enable insecure HTTP by setting OAuthAuthorizationServerOptions property AllowInsecureHttp = true

Answer №2

I recently encountered a similar issue related to CORS. Although my CORS code has been functioning properly for months, I am now facing a "Failed to load resource" error indicating a different underlying cause.

For those experiencing similar difficulties, I recommend looking into this helpful resource: https://github.com/MashupJS/MashupJS/blob/master/docs/mashupApi/WebApi-Cors-Chrome.md

If you're struggling with setting up a WebApi that supports CORS, consider creating one from scratch using the insights shared in the linked document. Even after consulting Microsoft's resources without success, taking matters into my own hands and writing my own solution proved effective.

Best of luck in resolving your CORS issues!

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

Having trouble accessing the input class with jQuery

When I click the "Reset To Default Settings" button in my form, I want to clear the default colors in my 4 color pickers. Each of them has an input type text field with the class anyicon-form-colorpicker. To achieve this, I locate the <a> tag and use ...

Empty req.body object in Node.js

I came across this code snippet: const bodyParser = require("body-parser"); const express = require("express"); const app = express(); app.use(express.json()); app.use(bodyParser.json()); app.post("/api/foo", (request, response) => { let foo = { ...

What could be causing the issue with the JS function that is preventing the button from

I am generating a button dynamically using my JavaScript function and then adding it to the DOM. Below is the code snippet: var button = '<button id="btnStrView" type="button" onclick=' + parent.ExecuteCommand(item.cmdIndex) + ' c ...

Obtain identical encryption results with CryptoJS (JavaScript) and OpenSSL (PHP)

I am in the process of integrating a PHP encryption function into a ReactJS application. I have a requirement to transmit the token in a specific format that was generated using the OpenSSL library function (openssl_encrypt). It has been observed that the ...

Do you have any queries regarding JavaScript logical operators?

I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered. va ...

Error message: "SyntaxError: Unexpected token import was not caught by the foundation"

I have recently taken over development from a previous developer who integrated Zurb Foundation as a framework into our website. The Foundation framework was installed using npm. I am encountering errors in the console related to all of the foundation java ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

Certain iFrame instances are unable to display specific cross-domain pages

I'm currently working on a project to create a website that can embed external cross-domain sites, essentially like building a browser within a browser. I've been experimenting with using iFrames for this purpose: While it works for some pages, ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

Looping through a series of JavaScript objects in a JSON

I've encountered an issue when trying to run a loop with a JSON query inside it. Here's what my code looks like: for (var i = 0; i < numitems; i++) { var currentitem = items[i]; $.getJSON("http://localhost/items.php", {'itemname&ap ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

What is the best way to display JSON within a partial?

Within my Rails app, I have implemented a JavaScript graph. Whenever I click on a circle in the graph, it displays the name of the corresponding user. Now, my goal is to retrieve additional information from the related database table based on this user&apo ...

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

Issue with third-party react module (effector) causing Webpack error

UPDATE: After struggling with my own custom Webpack setup, I decided to switch to using react-scripts, and now everything is compiling smoothly. It seems like the issue was indeed with my Webpack/Babel configuration, but I still can't pinpoint the exa ...

Using Firefox to cache Ajax calls after navigating back in the browsing history

Currently, I am utilizing an ajax call to invoke a php script that waits for 40 seconds using sleep and then generates the output RELOAD. Subsequently, in JavaScript, the generated output is validated to be RELOAD, following which the call commences again. ...

Retrieving users by their Id's from MySql database using NodeJS

Goal: I aim to gather a list of users from a table based on the currently logged-in user. I have successfully stored all user IDs in an array and now wish to query those users to display a new list on the front end. Progress Made: I have imported necessa ...

Clickable element to change the display length of various lists

I am working on a project where I have lists of checkboxes as filters. Some of these lists are quite long, so I want to be able to toggle them to either a specified length or the full length for better user experience. I have implemented a solution, but th ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...