The preflight request returned an unexpected status code of 404 after a Jquery AJAX POST

It's quite frustrating to encounter this specific error in the console. Despite the abundance of similar questions on stackoverflow, I have thoroughly researched and confirmed that CORS is enabled in my Web API 2 web service. Yet, the error persists.

Below is my Web API 2 code snippet:

namespace WebApi.App.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ServiceController : ApiController
    {
        [HttpGet]
        [Route("GetData")]
        public IHttpActionResult GetEmpData(DATAvars theDATA)
        {
            return Ok("WORKED! " + theDATA);            
        }

        [HttpPost]
        [Route("PostData")]
        public IHttpActionResult PostEmpData(DATAvars theDATA)
        {
            return Ok("WORKED! " + theDATA.theID);
        }
    }

    public class DATAvars
    {
        public string theID { get; set; }
        public string empImg { get; set; }
    }
}

ALSO

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule"/>
</modules>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

ALSO

namespace WebApi.App
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            config.MapHttpAttributeRoutes();
            config.EnableCors();
        }
    }
}

ALSO

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
    { 
        //These headers are handling the "pre-flight" OPTIONS call sent by the browser
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    } 
    } 
}

Next, here is my AJAX call code (hosted on a different domain):

$.ajax({
    type: "POST",
    crossDomain: true,
    url: "http://dev-blahblah/newWS/PostData",
    beforeSend: function (xhrObj) {
        xhrObj.setRequestHeader("Content-Type", "application/json");
    },
    data: {
        theID: "2135648792",
        empImg: "false"
    },
    dataType: "json",
    success: function (data) {
        console.log(data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest);
    }
});

This is the error displayed in the console: https://i.sstatic.net/vaANs.png

The Console Network indicates: https://i.sstatic.net/ceBSy.png

Failed to load resource: the server responded with a status of 404 (Not Found) index.html:1 XMLHttpRequest cannot load . Response for preflight has an invalid HTTP status code 404

Comparison between the same request in POSTMAN: https://i.sstatic.net/mwxiT.png https://i.sstatic.net/c1aNo.png https://i.sstatic.net/GZUw9.png https://i.sstatic.net/SuZin.png

I have dedicated significant time trying to resolve this issue with countless Google searches for solutions. While examples can be found, none seem effective.

I would greatly appreciate assistance on resolving this matter and getting it to function correctly with JQUERY AJAX.

-Successfully operates on the same domain in CHROME = WORKS

-Does not operate on a different domain in CHROME = DOES NOT WORK

-Successfully operates on the same domain in IE = WORKS

-Successfully operates on a different domain in IE = WORKS

Answer №1

Implemented the following configuration snippet in my web API's web.config file to resolve the 404 error issue.

<handlers>
  <remove name="WebDAV"/>
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
</handlers>

Answer №2

While removing WebDAV didn't solve the issue due to potential global server policies, I found success with this solution:

<system.webServer>
    <security>
        <requestFiltering>
            <verbs applyToWebDAV="false">
                <add verb="DELETE" allowed="true" />
                <add verb="PUT" allowed="true" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>

The addition of

<add verb="OPTIONS" allowed="true" />
was the key difference that resolved the issue.

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

Issues arose when attempting to navigate in a JavaScript handler within ASP.NET MVC

As a newcomer to Javascript, I hope my question isn't too basic. I have a button in my ASP.NET MVC 4 view: <input name="button" type="button" id="button1" value="Click me1"/> In order to create a click handler for the button, I've added ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...

Sending Data from Clicked Button to Another Component as a Prop

I am struggling to figure out how to pass a value that is set inside a button to a child component. Essentially, I want the value of the clicked button that displays a percentage to be passed as a prop value. This prop value should update depending on whic ...

Calculating the sum of all values in the database

In my database, I have a value called task_time. I want to add this value to itself so that the total time is calculated as totalTime = task_time + task_time + ... + task_time. This is how I retrieve the data: function getEndTasks() { $http.get(& ...

Comparing OLOO and OO in ReactJS for front-end web development

After reading Kyle's book, I found it to be extremely informative. However, I am a bit perplexed by the discussion in "You Don't Know JS: this & Object Prototypes". The series argues that the "Object Linking to Other Object" design pattern is cl ...

Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application. Requirement: User must be authenticated User can read/write their own data entries User can read data with "visibility" field set to "public" User can rea ...

Create a customized menu with jQuery that disappears when hovered over

Check out this menu I've created: http://jsbin.com/useqa4/3 The hover effect seems to be working fine, but I'm looking to hide the div #submenuSolutions when the user's cursor is not on the "Solution" item or the submenu. Is there a way to ...

Tips for incorporating JavaScript into elements that have been modified using jQuery's .html() method

Consider this example: $('#key').on('click', function(){ $('.task').html("<button id='key'>Button</button>"+Date()); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.j ...

Receiving and transmitting messages repeatedly in Discord.JS

Currently, I am developing a simple bot. Interestingly, the bot seems to be responding multiple times to a single command. Here is the code snippet: const Discord = require('discord.js'); var bot = new Discord.Client(); const PREFIX = "+"; var ...

Tips for effectively storing and organizing database queries in a c#/.net project

I am embarking on my first c# project and facing the challenge of connecting to a database server for multiple read-only queries. I am currently hardcoding query strings in the C# source files whenever needed, but this approach is proving to be difficult ...

Artwork expanding incorrectly on HTML canvas

I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected. My assumption is that the elements are being ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

Add the user's input text to a modal in C# MVC 5

If my status changes, I want to add another text box or text area for additional comments. In the photo provided, this has been implemented but the positioning is not quite right due to issues with the modal. Below is a snippet of my code where you can ta ...

What is the method for altering the background color with JavaScript in CSS?

I need assistance with changing the background color using JavaScript. Specifically, I want to change the color of the background property that is located within .diagnosis-kit-inner .nav-tabs .nav-item.active:after. Can someone provide guidance on this? T ...

How to extract text from a <th> element with c#

Help needed in retrieving text from an HTML table We attempted to use the following method: tblGridHeader.Rows[0].InnerText.ToString() However, encountered this error message: "HTMLTableRow" does not support InnerText property. We also tried using ...

I'm having difficulty implementing a vue-awesome icon on my project

I am attempting to utilize the standard window-close icon from vue-awesome. I have imported my vue-awesome using the following code: import 'vue-awesome/icons'; import Icon from 'vue-awesome/components/Icon.vue'; Vue.component('i ...

Is JavaScript asynchronous when it comes to manipulating the DOM?

While conducting Javascript tests on the Android browser, I monitored the number of instruction counts executed on the CPU. The test code for JS is straightforward and embedded within HTML files located in the local directory of an Android device, not on a ...

When my View is deployed, the relative URL path breaks

As I work on my ASP MVC app, I encountered an issue with the path to a Partial View when using Javascript. The path needed to be hardcoded and differs between Development and Production environments. Specifically, in Dev there is no App specification, whe ...

Is there a way for me to detect click events on Windows notifications?

Currently, I am attempting to send notifications through the node-notifier package. The goal is for a click on the notification to lead to a specific link. However, I am encountering difficulties in listening to the click event - the events provided by the ...

Sending a Large File with Axios

I am facing a challenge while trying to upload a large JSON file containing at least 400,000 objects into my database. When I attempt to post only 20,000 objects at a time, everything works smoothly, indicating that the issue lies with the size of the JSON ...