Using AngularJS $http.post() to send JSON data to a WCF REST service is unsuccessful in Chrome but works fine in IE

1- In the Application_Start() Event of the global.asax file of a WCF project, all Header Settings were added. http://www.codeproject.com/Articles/845474/Enabling-CORS-in-WCF

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST,PUT,DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        } 
    }

2- CORS was enabled inside the WebApiConfig file http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

    }
}

3- The [EnableCors] attribute on the action method of the controller was used to enable CORS for a single action.

public class VideoController : ApiController
{
[Route("PostComment")]
[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "POST")]
public HttpResponseMessage PostComment([FromBody] DTOUserComment comment)
    {
        HttpResponseMessage response = null;
        try
        {
            IVideoDetails vdo = BaseServices.videoDetails();
            vdo.UpdateComments(comment);
            response = Request.CreateResponse(HttpStatusCode.OK, "Success");
        }
        catch (UnauthorizedAccessException ex)
        {
            response = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
        }
        catch (Exception ex)
        {
            response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
        return response;
    }

}

4- Data was posted from Angular js using $http.post()

$scope.publishComment = function () {
        var myJSONData ={"UserName":"Asif"};
        var req = {
            method: "POST",
            url: "http://localhost:55590/api/BaseAPI/postcomment",
            data: myJSONData              
        };
        $http(req).then(function(response){
        alert("success");
},function(reason){
alert("error"); 
});

Before Adding CORS, the webapi response code showed "405 Method not Found" Error in Chrome browser: https://i.sstatic.net/udx20.jpg

After adding CORS inside WebAPi, the response status code changed to "200 OK", but the Request Header still showed "OPTION" instead of "POST" which caused data posting failures:

https://i.sstatic.net/uQwsf.jpg

Any assistance would be greatly appreciated. Thank you.

Answer №1

After making some modifications to the Global.asax.cs file, I was able to resolve the issue at hand by adjusting the header information:

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

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            // Handling the OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Api-Version");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

In my Angular code snippet, here are the adjustments made:

        $http.defaults.useXDomain = true;
        delete $http.defaults.headers.common['X-Requested-With'];

        var req = {
            url: BASEURL + 'Login',
            method: "POST",
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            data: {
                userName: username, password: password, isPersistent: true
            }
        }

        $http(req)
            .success(function (response) {
                console.log(response);
                callback(response);
        });

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 radar chart created with amchart.js disappears when placed within bootstrap columns

I'm encountering an issue while trying to display radar charts using amchart.js in bootstrap columns. The "amStockGraph" charts render perfectly, however, the radar charts appear blank with no errors in the console. Any advice on this matter would be ...

Experimenting with AngularJS using karma and jasmine

I'm currently working on writing some unit tests. I encountered an error stating that angular is undefined, so my solution is to add the angular js file along with my other js files. In order to achieve this, I am attempting to npm install it... { ...

To make the label font size larger when it appears on hover in chart.js

I have been attempting to increase the font size of labels that appear on hover in chart.js. I am also trying to customize the text of the label, but so far, I have not been successful in increasing its font size. var myPieChart = new Chart(ctxP, { ...

Unlocking the Mystery: Detecting User Cancellations in ngCordova Email Composer

Recently, I integrated the ngCordova Email Composer plugin into my Ionic v1 app. It serves as a wrapper for the cordova-plugin-email-composer and has been working well. However, I am facing an issue when trying to determine if the email was sent successful ...

Adjust the height of a div using jQuery animate based on the amount of text within

I have created a basic animation feature where users can click on an expanding box. I am looking for a solution that does not involve using a plugin. Currently, the code looks like this: $('#one').css("height", "22"); $('#t1').cli ...

Is it possible to utilize Angular's dependency injection in place of RequireJS?

As a newcomer to Angular, I am wondering how I can organize my code into separate files without using requirejs or any other framework. After watching a brief introductory video, it seemed possible. Currently, my app looks like this and functions well: v ...

Launching the server with a custom path in Nuxt.js: Step-by-step guide

My Nuxt.js application has several nested routes. . ├── index │   ├── _choice │   │   ├── city │   │   │   ├── index.vue │   │   │   ├── _zipCode │   │   │   │   ├── i ...

Is it possible to create perfectly aligned pie charts in nvd3? Check out this code snippet to see how it can be achieved: http://plnkr.co/edit/w0LewO7TmG6Lx

Having just started with AngularJS, I am facing a challenge in creating two equal-size pie charts and aligning them horizontally. Currently, they are aligning vertically - the first chart on one row and the second on the next. Does anyone know how to alig ...

What is the most effective way to open a jQuery dialog using Angular?

Check out this HTML snippet: <div ng-controller="MyCtrl"> <a ng-click="open()">Click to Open Dialog</a> <div id="modal-to-open" title="My Title" ui-jq="dialog" ui-options="{width: 350, autoOpen: false, modal: true}"> ...

In Internet Explorer, the list items are overlapping, while functioning perfectly in all other web browsers

I've encountered a strange issue with my list item in Internet Explorer. Despite working perfectly in Chrome and other browsers, it fails to function properly in IE. I've built this application using the Vue framework and have faced various probl ...

What is the reason behind Node's error callback returning undefined first?

Whenever I try to run the error callback function, the code below returns undefined. I'm puzzled by why the JSON isn't being returned when the console log displays the entire query. Take a look at the function that is triggering the json to be l ...

"Connection Failure: MongoDB Server Unreachable"`

I've been working on a basic web application using MongoDB, Express, and NodeJS. Unfortunately, I've encountered an issue where I cannot connect to MongoDB and keep receiving the following error message in the terminal: (node:28265) UnhandledPro ...

Display the array in the Vue view section without using curly braces

I am trying to display the following array in the view section without braces and quotations. Currently, it is showing with exact array containing braces and quotations. Array ["WHATSAPP", "2G", "CLIQ"] Code <v-col cols=& ...

Using SailsJS to populate attributes transmitted through socket.io's publishUpdate event

Utilizing the built-in socket capabilities of SailsJS has proved to be quite effective for me so far. However, I've encountered a challenge that I haven't been able to find any information on. In my model, I have set it up to populate certain at ...

Is it possible to safeguard undisclosed data in browser console?

Can JavaScript be employed to prevent users from editing hidden fields through the browser console? ...

Guide to implementing a feature where clicking on a specific section of the background image triggers a transition to another website using HTML

Is it possible to set up a background image with clickable regions that direct users to specific websites? ...

Is there a way to automatically remove flash messages in AngularJS after a certain period

For controlling the timing of clearing my FlashService message, I attempted to implement a timeout feature. However, it seems to function more like a delay. FlashService.Success(("Removed Successfully"), false); In this instance, I have used false as a c ...

AngularJS - Controller routing to open link in new tab based on condition

Within my application, there are two distinct types of profiles available for organisations. When a user interacts with a profile name, the system must first determine if a premium profile exists for that organisation. If a premium profile is found, the us ...

Having trouble with missing elements while looping through Javascript Node.AppendChild()?

I encountered an issue with a basic function designed to relocate items from one div to another using a drag and drop widget. It seems that when multiple items are being moved, the appendchild function is modifying the list directly and causing elements to ...

JavaScript code for converting a list into an array separated by commas

I have a function that is outputting a list like this: email1 email2 email3 … My goal is to convert this list into an array with the following format: email1, email2, email3, … Does anyone have any suggestions on how I can achieve this conversion? ...