Access to web API from a different domain using $http AngularJS request was blocked due to a denied cross-domain localhost

Using AngularJS hosted on an ASP.NET server. Making a call to a web API. When making a POST request to the web API without parameters, it works. However, when passing parameters to the POST request, it returns the following error: Error: XMLHttpRequest cannot load http://localhost:60117/api/Parts. The response to the preflight request does not pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:64658 is not allowed access.

Note: CORS has already been enabled through NuGet. [EnableCors("*", "*", "*")] is included in the webapiconfig.cs file.

var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

The following is my request header:

OPTIONS /api/Parts HTTP/1.1
Host: localhost:60117
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:64658
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36    (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:64658/app/views/Index.html
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8

When adding the following code to the web.config file, it results in a multiple accept verb error:

<httpProtocol>
    <customHeaders>
        <clear/>
        <add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE"/>
        <add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type"/>
        <remove name="X-Powered-By"/>
    </customHeaders>
</httpProtocol>

Updated:

Now receiving the following message in response to the request:

The requested resource does not support the HTTP method 'POST'.

AJAX call:

$http({
        method: "POST",                       
        url: config.APIURL + 'Parts',
        data: {'final':'final'}                       
});

Any assistance with this issue would be greatly appreciated. I am currently stuck and unable to progress.

Answer №1

When there is a difference in port, it is considered a cross domain request, leading some browsers to send preflight OPTIONS requests.

It is important to configure your server to accept these requests and respond with a 200 OK status code. You can find more information on how to do this at the following URL:

http://enable-cors.org/server_aspnet.html

Answer №2

If you're facing challenges with your current methods, consider giving this approach a try. Within your Globax.asax file in your WebApi, include the following method:

protected void Application_BeginRequest()
        {
            if (Context.Request.HttpMethod == "OPTIONS")
            {
                Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
                Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");                    
                Context.Response.End();
            }
    }

Additionally, within your WebApi Config, incorporate the following method call to activate CORS:

  config.EnableCors();

Finally, in your controller(s), apply an attribute similar to the following:

[EnableCors(origins: "*", headers: "*", methods: "*")]

We hope this guidance proves helpful. For more detailed information, feel free to visit this webpage https://msdn.microsoft.com/en-us/magazine/dn532203.aspx. Thank you for considering these suggestions.

Answer №3

Make sure to include the CorsMessageHandler class in the server to enable HTTP request handling.

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

JavaScript failing to render AJAX request

I have a website that utilizes AJAX to fetch data in JSON format from the backend and then displays it on the page. The website is built using MVC .NET framework. Below is the function responsible for loading events from the backend: function initEvents( ...

Is there a way to manage Firefox using R to manipulate AJAX/Javascript functions?

I'm currently exploring ways to control a web browser, preferably Firefox, using R scripts to extract information hidden behind AJAX and Javascript on websites. For instance, how can I retrieve the data in the "Modell" field at ? It seems that Gabe B ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

Are iFrames being utilized for third-party applications?

I am looking to create a web application that can be extended by other developers with their own applications. Would using iFrames, similar to how Facebook does it, be the best approach? Is this considered a good practice in web development? Are there a ...

Tips for animating a div twice within the success function

Here is the current AJAX script I have implemented: $.ajax({ type: 'post', url: 'action.php', success: function () { $(".success").show().delay(300).fadeOut(); $(".success ...

Using an AJAX request to communicate between the controller and view in Codeigniter

I'm a newcomer to CodeIgniter and I want to send a JSON encoded value to the view for further processing. Here is the code snippet: Jquery post: $('#btn_reset_password').click(function(){ var parameters = $('#reset_password_form&a ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

"Encountering a problem with posting API requests using Express

I've encountered a problem where I keep receiving a 404 error when trying to post to a specific route. Here's the code snippet: app.js (code snippet for app.js) .... module.exports = app; api.js (code snippet for api.js) .... module.export ...

The back to top feature is malfunctioning when navigating to a new page

I've been working with jQuery Mobile to create some pages and wanted to add a "back to top" element. It's been functioning well, but I've encountered an issue. When I navigate from one page, let's say #sport, back to #restaurants after ...

Is it possible to verify with Jest that ReactDOM.render has been called if it's enclosed in a conditional statement?

I have a React component that conditionally calls ReactDOM.render when root === true to satisfy flow: import React from 'react' import ReactDOM from 'react-dom' import App from './App' const root = document.getElementById(& ...

Enhance the user experience by implementing a smooth transition effect when loading new pages

Recently, I've been exploring a method to load content from an external HTML file using AJAX on my website. While it's working well, I'm now interested in adding a page transition effect when the content changes. Specifically, I'd like ...

Symfony2 does not receive any feedback from the Ajax request

Perform an ajax POST request with no response: Here is the ajax request code snippet: $.ajax({ method: 'POST', url: "{{ path('app-like-add') }}", data: { imageId: id }, success: function(response) { ...

The Javascript Date constructor struggles to interpret date strings in certain timezones that are not enclosed in brackets

Take a look at the examples below: new Date("Wed, 28 May 2014 09:50:06 EEST"); // Invalid Date new Date("Thu, 26 Jun 2014 09:09:27 EDT"); // OK, is parsed new Date("Wed, 28 May 2014 09:50:06 (EEST)"); // OK, is parsed new Date("Thu, 26 Jun 2014 09:09:27 ( ...

While utilizing Ajax with Spring, it is possible to send a JavaScript object and receive it as a custom object. However, there was an issue with

One of my challenges in Java is working with a custom class that looks like this: public class AddressesVO { private Long addressId; private String address; public Long getAddressId() { return addressId; } public void setAddressId(Long addressId ...

Pass the identical event to multiple functions in Angular 2

On my homepage, there is a search form with an input box and select dropdown for users to search for other users by location or using html5 geolocation. When a user visits the page for the first time, they are prompted to allow the app to access their loca ...

Unlocking the Secrets: Expert Methods to Obtain Assets through HttpClient in Angular

After researching similar inquiries, such as the response provided in this thread, it seems that downloading or reading files from the assets directory can be accomplished easily by utilizing the get method of the HttpClient. For instance, if I have a Down ...

The animation for the CSS gradient background is failing to animate

After finding a similar code snippet used for backgrounds, I made some modifications to suit my needs. However, when attempting to implement it or any animation, nothing seems to be working. Even simple animations are not functioning as expected. While I a ...

What is the best approach for running a database query using the value selected from a form dropdown?

Currently, my application server is ColdFusion and I am using SQL Server for the database. Within a select form element on my webpage, users can choose from a list of vehicles such as Volvo S60, BMW M6, and VW Jetta. Once a user selects a vehicle, I need ...

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...

In IE8, submitting an Ajax request almost always results in an error being

This piece of code seems to be causing some trouble, as it works fine in all browsers except for IE8 on an XP machine. No matter what I try, the error function keeps getting triggered specifically in IE8. I've experimented with different dataTypes lik ...