Successfully connected with status 200, however, an angular promise is triggering an error due to the absence of 'Access-Control-Allow-Origin' header

Initially, I have confirmed that CORS is enabled and functioning in my web API by successfully sending post/get requests from another controller. However, when CORS is disabled, I encounter issues with posting/getting data from the server. The same situation applies to obtaining a token; once CORS is disabled on the web API, I no longer receive a valid response. But currently, I am receiving a valid response.

I am attempting to retrieve a token from the web API using Angular Resource and a promise. In Fiddler, I can see status 200, indicating that I am receiving a token back. The JSON specifies "bearer token = x," which looks good. Postman also shows successful results. But when checking the debug console, I notice that the promise is throwing an error, despite Fiddler and Postman showing me a valid JSON file with a status of 200.

// Controller
.controller('LoginCtrl', ['$scope', 'Token', function ($scope, Token) {
    $scope.login = function () {Token.save('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592c2a3c2b3738343c642d3c2a2d686b6a192d3c2a2d773a3634">[email protected]</a>&password=Test123!!&grant_type=password')
            .$promise.then(function (response) {
            console.log(response);
        });
    };
}]);

In my factory:

.factory('Token', ['$resource', function ($resource) {
    return $resource(baseUrl + 'token', null, {
        save: {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': '*/*'
            },
        }
    });
}]);

The response I receive in Developer Tools console is:

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Content-Type":"application/x-www-form-urlencoded","Accept":"/"},"data":"[email protected]&password=Test123!!&grant_type=password","url":"http://localhost:55126/token"},"statusText":""}

I am absolutely certain that I am receiving a valid JSON object from the /token call. Thank you in advance.


Update

XMLHttpRequest cannot load localhost:55126/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:9000'; is therefore not allowed access. angular.js:14642 –

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transfor‌​mRequest":[null],"tr‌​ansformResponse":[nu‌​ll],"jsonpCallbackPa‌​ram":"callback","hea‌​ders":{"Content-Type‌​":"application/x-www‌​-form-urlencoded","A‌​ccept":"/"},"data":"‌​username=test123@tes‌​t.com&password=Test1‌​23!!&grant_type=pass‌​word","url":"localho‌​st:55126/token";‌​},"statusText":""}

These two error lines appear consecutively.

Answer №1

It appears that the solution is related to CORS. Despite installing NuGet Microsoft.AspNet.WebApi.Cors and implementing:

config.EnableCors(new EnableCorsAttribute("", "", "*"));

While this resolved issues with regular controller requests, I discovered that when requesting a token, I needed to also install NuGet Microsoft.Owin.Cors and add:

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

In the web API configuration section of the application. Thank you for your assistance.

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

Enhancing User Experience: Creating a Vue Button Component for Adding Items to Cart with the Power of Axios and Laravel Backend Integration

I have recently developed a Vue3 shopping cart with an "Add One" button feature. When the user clicks this button, it updates an input field of type "number" and sends a request to update the database using Axios along with Laravel's createOrUpdate me ...

retrieve a response from the server during an ajax request when submitting a file using a multi-data form

I'm encountering a slight issue with my project. I have multiple JSPs and Java classes in my setup. In one of the JSP files, I've created a form consisting of only an input type="file" and type="submit". After that, I make an AJAX call to send al ...

Swapping out the initial hue and toggling between two different colors

Is it possible to keep the color removed after pressing the 1st play SVG, while having two other colors switch back and forth between each other? https://jsfiddle.net/x0pu2c31/ The current colors are Blue. Once one is pressed, I want the colors to switch ...

Looking for assistance with regards to submitting an event

I have been working on developing a form and validating it using jQuery before submitting it to the server. Everything seems to be functioning correctly except for the function on the submit event. The form is being submitted with errors and upon checking ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

Vue fails to receive updates from Firestore until the page is manually refreshed

I set out to develop a task tracker app using Vue. As I neared completion of the project, I encountered an issue - when adding a new task, it would not change the reminder status unless I reloaded the page. Here is the code snippet from my Home.vue file: & ...

The number of columns in the DataTable does not align with the columns in the DataBound DataGridView

I have been working extensively with both the DataGridView and DataTable, but I am facing a perplexing issue. Occasionally, the column count in my DataGridView does not match that of the associated DataTable, despite setting the DataSource property correct ...

How to Access ViewBag Value from Asp.Net in AngularJs Controller

Just getting started with AngularJs and encountering an issue with passing a value from a .Net MVC View to an AngularJs Controller. Here's the code snippet in question: AngularJs controller snippet: app.controller("RatingApiController", function ($s ...

Transforming the text color after clicking on it on Squarespace - here's how to do it!

How can I make text change color upon clicking in Squarespace? Where should I place the block id in the code to target a specific block? Check out the code snippet I've been experimenting with: <script> document.getElementById('chang ...

Utilizing Angular 2's moment Pipe for Manipulating Time in JavaScript

I'm currently utilizing Ionic3 along with angular2-moment. The pipe is functioning flawlessly for formatting a timestamp, like so: html <ion-note class="small-text-search"> Last Online {{personModel.lastAccessDate | amTimeAgo:true}} ago < ...

"Discovering the referring page URL in Next.js: A Step-by-Step

On a webpage, I use router.push('destination-url') to redirect users to an external link. I want to determine if the user has navigated back from the redirected page or not. If they arrived from an external link, they should not be allowed to re ...

"The Vue.js/JavaScript object updates, but the changes are not being displayed in the document object model (DOM

Currently, I am endeavoring to iterate through an array of objects and display them as list items. There is a click listener that introduces a custom property to the object, and a class binding depends on the value of that property. Would you mind reviewin ...

Divide the row once you've reached the end of the container

I am facing an issue with the code snippet provided below where the images fetched from the database seem to break the DIV and cause an overflow. My goal is to have the images break and start a new line once they reach the end of the DIV. Unfortunately, ...

I'm having trouble understanding why this code is causing confusion for the user's selection during a specific part of the execution. I can't seem

In this memory game, event listeners respond to user input after a sequence of colored divs change color to appear illuminated. The expected behavior is that once the user clicks on the correct div in the right order, the sequence restarts with an additi ...

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

Accessing information from a database using SQL commands in C# programming

I'm working on creating a book management system using C#. The data for the books is stored in a database with the extension .ACCDB. My first task is to retrieve the bookIDs associated with a specific series by executing the following SQL query: sql ...

JQuery for personalized path animations

After developing an android app that sends onTouchEvents points to a web server, I've been able to retrieve motion points JSON data using Ajax. Here is a snippet of the data: {"data":[ {"x":224.28035,"y":235.4906}, {"x":263.32916,"y":219.45718}, {"x" ...

Struggling to store a new user in Firebase Database

I have been researching extensively and am struggling to get any data to show up in the firebase database. I am aiming for this specific structure: "my-app-name": { "users": { "uid-of-user": { "email": "<a href="/cdn-cgi/l/email ...

Tips for implementing vue-multiselect tagging within an ASP.NET solution in Visual Studio 2017

I am attempting to implement vue-multiselect tagging, but encountering some errors such as: "vue.js:634 [Vue warn]: Unknown custom element: - have you registered the component correctly? For recursive components, ensure that the "name" option is provided ...

Retrieving a universal variable within AngularJS

Is there a way to initialize an Angular model using a JSON object that is embedded within an HTML page? Take this as an example: <html> <body> <script type="text/javascript" charset="utf-8"> var tags = [{&q ...