Invalid HTTP status code 400 received as response for preflight request in Web API MVC

We have developed a web api and are currently attempting to send data via ajax using that api. The web api works perfectly for post requests when tested with the Postman plugin, but we are facing issues when trying to post data through an ajax call using json format.

The specific error we are encountering is XMLHttpRequest cannot load http://localhost:922/api/leaddetails/createlead. Response for preflight has invalid HTTP status code 400

Below is the code snippet for the ajax call:

function SaveLead() {

        var Lead = {
            "lead_owner": "Pritam",
            "company_name": "C",
            "title": "T",
            "first_name": "Santosh",
            "last_name": "M",
            "address1": "Rajasthan",
            "address2": "d",
            "city": "d",
            "state": "d",
            "country": "d",
            "postal_code": "d",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="700611091130171d11191c5e131f1d">[email protected]</a>",
            "phone": "d",
            "website": "d",
            "mobile": "8787878787",
            "lead_status": "d",
            "lead_source": "d",
            "industry": "d",
            "annual_revenue": "d",
            "skype_id": "d",
            "campaign_source": "d",
            "description": "d",
            "created_by": "A",
            "updated_by": "a"
        };

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: 'http://localhost:922/api/leaddetails/createlead',
            data: JSON.stringify(Lead),
            crossOrigin: true,
            dataType: "json",
            success: function (res) {
                alert("The result is : " + res);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        })

    }

Here is a snippet from my web.config file:

<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" />
  (...)

I have successfully tested posting data using the Postman plugin, which worked flawlessly.

Answer №1

After consulting with a friend, I received a potential solution. Making adjustments to the ajax syntax seemed to do the trick for me.

    var apiurl = 'http://localhost:922/api/leaddetails/createlead';
    var a = new XMLHttpRequest();
    function SaveLead() {
    var Lead = {
            "lead_owner": "Pritam",
            "company_name": "C",
            "title": "T",
            "first_name": "Sourav",
            "last_name": "M",
            "address1": "Bhilai",
            "address2": "d",
            "city": "d",
            "state": "d",
            "country": "d",
            "postal_code": "d",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afcebf3ebcaede7ebe3e6a4e9e5e7">[email protected]</a>",
            "phone": "d",
            "website": "d",
            "mobile": "8787878787",
            "lead_status": "d",
            "lead_source": "d",
            "industry": "d",
            "annual_revenue": "d",
            "skype_id": "d",
            "campaign_source": "d",
            "description": "d",
            "created_by": "A",
            "updated_by": "a"
        };



        a.open('POST',apiurl,true),
         $.ajax({

             url: apiurl,
             type: "POST",
             ContentType: "application/json; charset=utf-8",
             data: Lead,
             crossOrigin: true,
             dataType: "json",
             cache: false,
             complete: function (res) {
                 alert("Data Added Successfully");
             },
             error: function (xhr) {
                 alert("Error");
             }
         })

    }

Grateful for everyone who contributed their insights.

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

Splitting the package.json file to separate the front-end and back-end components while utilizing shared

Currently, I am working on a project that involves a separate frontend (webpack) and backend (express/mongodb). My goal is to separate the dependencies in the package.json file while still being able to share certain logic/utility code between them. How ca ...

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

Create a dynamic HTML table in React by leveraging arrays

I am working with two arrays: headings=['title1','title2'] data=[['A','B'],['C','D']] How can I efficiently convert this data into an HTML table that is scalable? title1 title2 A B ...

utilizing ng-repeat for populating data from a JSON document

Recently I've started learning about angularjs and I'm looking for a way to present the information from this json file using ng-repeat. However, I'm a bit puzzled by the fact that there is a numerical value serving as the key for each obje ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

How can I extract the JSON value from an input form in CodeIgniter?

I am working with a json variable and I need to send it in json format. $json_value = json_encode($my_array); ... echo '<input name="myvalue" type="hidden" value="'.$json_value.'" />'; ... However, when I try to access it in my ...

Several pictures are not displaying in the viewpage

I have a controller method set up to fetch files from a specific folder. public JsonResult filesinfolder(ProductEdit model) { string productid = "01"; string salesFTPPath = "C:/Users/user/Documents/Visual Studio 2015/Projects/root ...

Tips for utilizing insertion mode in Ajax

I have a question regarding using Ajax in my Asp MVC4 project. I am facing an issue where only the last data appears when I try to insert data into my index using Ajax. The other data seems to be getting crushed. Is there a way for me to use an insertion m ...

Error encountered: `TypeError: Unable to access undefined properties (specifically, '0') within the Simple React Project`

Currently in the process of learning React and working on a simple photo application. Encountering an issue: Collection.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading '0') Why is this happening? Everything was functioni ...

What is the best method to determine if a text box is filled or empty?

I need to verify whether a text box is populated with a name. If it is empty, an alert message should be shown upon clicking the submit button, and the page should not proceed with submitting the blank value. If there is a value in the text box, then that ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Learn how to incorporate additional rows into a table by pressing the plus button within the table with the help of Angular

I require some assistance. I am looking to dynamically generate a row after clicking on the plus button using angular.js. The newly created row should contain an ID and model generated dynamically. Here is an overview of my code: <table class="table ta ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

Exploring the method to search across various fields in Vue.js 2

In my Vue.js 2 application, I am attempting to search or filter through three fields: firstname, lastname, and email. Unlike Vue 1, Vue 2 does not include a built-in filter method. As a result, I have created a custom method that can only filter through on ...

What could be causing the issue with retrieving HTTP requests in Nest.js even after configuring the controller?

After the individual who departed from the company utilized Nest.js to create this server-side system. They established the auth.controller, auth.service, auth.module, auth-token, jwt.strategy, and jwt-payload, with everything properly configured. I verifi ...

Changes made to Objective C variables within an Async block do not affect the value of the Class variable

I am facing an issue with using my parsed JSON values from an async block in different methods and in the viewDidLoad function. In the async block, it returns the value properly, but in other methods, it just returns null. Below is a snippet of code from ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

Pass data dynamically to router in ExpressJS

Within my app.js file, there are several variables defined: var user = "max"; Additionally, there is a route function set up like so: app.post('/register', user.postRegister); In the /routes/user.js file, there is a module function structured ...

The Bootstrap Modal containing a JQuery Validation Form refuses to submit even after successful validation

UPDATE: To provide some context for the question, I have created another Fiddle that showcases the same form outside of the modal. Under the right conditions, such as entering an email address and clicking the Get Started button, the form submits correct ...