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

The peculiar actions of the Array.function(Object.keys(Obj[0]).map()) function

In my current code implementation, I have a hard coded [0] value that is used in rendering data for a table. However, instead of rendering only the first row as expected, it is displaying all rows. I am confused as to why this is resulting in rendering al ...

Mastering the implementation of owl-carousel in React.js

I'm currently working on a project that involves utilizing the react framework. My intention is to incorporate the owl-carousel, however, I've encountered issues as it fails to function properly. The following error keeps popping up: OwlCarousel ...

Tips for choosing or unselecting a row within a Table utilizing the Data Grid Mui

Is it possible to implement row selection and deselection in Mui without using the checkboxSelection prop? I am looking for a way to achieve this functionality in @mui/x-data-grid when clicking on a row. Below is the code snippet from the Table Component ...

Why can't JQuery/javascript's dynamic gallery's images be used as buttons instead of links?

I've been struggling with my online portfolio for several nights as I build my website. Despite exhaustive internet searches, I couldn't quite articulate my problem in words and tried multiple workarounds. To see the issue, please visit the beta ...

Invoke a function to retrieve HTML content from a controller method

public ActionResult MyActionMethod(MyModel model) { //some code string myVar= ActionMethod2(model).toString(); //use myVar Method3(myVar, otherVar); } public ActionResult ActionMethod2()(MyModel model) { return View(model); } private ...

Having trouble passing arguments to button methods in jasmine when applying vue and moment libraries

I am working on unit testing a Vue app using `jasmine` and `karma`. Here is an example of the code inside one of my components: After fetching data from a database with `v-for=(data,index)`, I am displaying the `data.date` in the template: <p class=&qu ...

Executing Ajax requests with callbacks in JavaScript/jQuery

I'm facing an issue where my functions are executing before Ajax requests (first fetching local JSON, then retrieving data from an online resource) have completed. For example, I want countTheMovies to run only after all the necessary information is ...

Knockout.js dropdown pre-selection in nested JavaScript objects is functioning smoothly in KO 2x versions, but there seems to be a compatibility issue with KO 3x versions

This is a sample data that will be loaded from the server in JSON format and constructed into the below object graph. It consists of an array of "Choice" objects, each with properties like id, name, stages, & currentStageId. The "stages" property in th ...

Having trouble with AngularJS ForEach and REST/JSON calls using $resource before the JSON data is ready?

My goal is to iterate through a resource using a controller and output each item in the JSON array with conditionals added later on. However, I am encountering an issue where it returns as "undefined": pfcControllers.controller('pfcArticlesCtrl' ...

Attempting to loop through a JSON data structure in a React component

Trying to add a toggle checkbox for each JSON value present. Here is an example of the json object pertaining to element { "sourceIP": { "Primary": ["237.100.100.3", "238.0.4.8"], "Secondary": ["237.0.1.178", "237.1.1.91"] }, " ...

After deploying to Heroku, the dynamic values in Angular are failing to appear

I recently encountered an issue with my Rails app that includes AngularJS components. While everything works perfectly on my local machine, I faced a problem after deploying it to Heroku. The dynamic Angular data values were not visible as expected; instea ...

executing a Prisma database migration with various schemas

I am currently immersed in a Prisma project where my goal is to create a node module that can be utilized by other projects. The challenge now is to ensure that the database stays synchronized with the models and the primary project, so all testing platfor ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...

How can I easily move from a shared page to a specific page in Angular 8?

Just stepping into the world of front-end development, I have a scenario where my menu page offers 3 options to navigate: Go to Arena. Go to Dungeon. Go to Battleground. However, clicking on any of these options leads me to a common page for character p ...

In search of a versatile multi-slide carousel solution for Angular JS

Hello everyone, we are looking to implement a carousel in our project. I came across the angular-carousel while searching online and found this helpful link http://www.bootply.com/94452. However, the carousel is written in jQuery and we will not be using ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

The input field becomes uneditable or non-editable when utilized in a directive alongside an ion-toggle

Link to Codepen demo This is the template code for my directive: <ion-toggle class="cw-alerttimebutton" ng-model="targetobject.isEnabled" ng-checked="targetobject.isEnabled"> <input type="text" ng-model="targetobject.time" value= ...

Comparison of MVC5 and Angular JS: Which is the better framework

For the past year, I've been immersed in ASP.NET MVC and have found joy in building SPA's using tools like: Partial views(via html.action() and renderPartial()) Ajax helpers (Ajax.Actionlink() and Ajax.beginform()) Now, I'm curious ...

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

What is the best way to utilize functions in Express to dynamically display content on my Jade template?

I have successfully implemented a user registration and login page, but now I need to determine what content to display based on whether the user is logged in. I found this solution: app.use(function(req, res, next) { db.users.find({rememberToken: req.c ...