What is the process for sending data in JSON format using the request payload?

My code sample seems to be facing an issue - even though I've set the method as post, it is displaying Request Method as OPTIONS and not setting the request payload.

I'm unsure if this is a CORS problem because it works fine with plugins like Postman and Rest Console in Chrome. Both tools show that the requested server has the correct parameters: Request Method is POST, Content-Type is application/json, and the data in $scope.data should be set as the request payload. What could be causing this issue?

angular.module('httpExample', []).controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.headers= {
                'Accept': '*/*',
                'Content-Type': 'application/json; charset=UTF-8'
            };
            $scope.method = 'POST';
            $scope.url = 'http://localhost:56652/reqresp.svc/json/post';
            $scope.data={"requests":[{"__type":"AuthenticateAndGetProsties:#LabOra.ProsteModul.ReqResp.Requests", "Authentication":{ "__type":"UserAuthentication:#LabOra.ProsteModul.ReqResp","Username":"xxx","Password":"yyyy" }}]};

            $scope.fetch = function() {
                $scope.code = null;
                $scope.response = null;

                $http({method: $scope.method, url: $scope.url,data: JSON.stringify($scope.data),headers:$scope.headers, cache: $templateCache}).
                    success(function(data,status) {
                        $scope.status = status;
                        //$scope.data =x2js.xml_str2json(data);
                        $scope.data =data;
                    }).
                    error(function( status) {
                        $scope.data = "Request failed";
                        $scope.status = status;
                    });
            };
        }]);
})(window.angular);

Answer №1

The issue at hand was related to CORS, as the Agatha rest service did not have it enabled. To enable CORS in Agatha, you need to include the following configurations in global.asax.cs:

        // Enable CORS
        response.AddHeader("Access-Control-Allow-Origin", "*");
        response.AddHeader("X-Frame-Options", "ALLOW-FROM *");

        if (context.Request.HttpMethod == "OPTIONS")
        {
            response.AddHeader("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
            response.AddHeader("Access-Control-Allow-Headers", "Accept");
            response.AddHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type");
            response.AddHeader("Access-Control-Max-Age", "1728000");
            response.End();
        }

Enjoy...!!!

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

What are the potential consequences if both jackson-jaxrs-json-provider and jersey-media-json-binding.jar are present in the class path located in the /WEB-INF/lib directory?

While working on a web application managed by Apache ant builder, we recently made an upgrade from jersey version 2.17 to 2.35 along with all the related dependencies in the classpath. However, post-upgrade, I encountered an error where the POST method arg ...

Is there a way to pass the values from the selected row into the modal whenever a click event is triggered on the table?

When a click event occurs on a table, my goal is to pass the values of the relevant row into the modal. However, I have encountered an issue where the values of the top row are always being passed into the modal instead of the row I clicked on. How can I e ...

What is the best way to locate and access a JSON file that is relative to the module I am currently working

I am in the process of creating a package named PackageA, which includes a function called parseJson. This function is designed to accept a file path pointing to a JSON file that needs to be parsed. Now, in another package - PackageB, I would like to invok ...

Error: The regeneratorRuntime is not defined. This error occurs in the Chrome console and is not related to the gulp/babel build process

Currently facing a perplexing issue that requires some assistance. I've been working on a WordPress theme using gulp & babel in a development environment, with separate hosting for dev and production. Thus far, building and testing the theme in t ...

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

Storing a Business Hierarchy in Browser Storage with JavaScript

I have developed a hierarchical tree structure on an HTML page where users can customize a company's organizational chart based on their needs. However, I am looking to store this structured data in local storage so that it can be utilized on another ...

Django form submission triggers Jquery modal to confirm object deletion

I'm currently working with Django and Crispy forms while also utilizing the Shopify Embedded Apps SDK. My goal is to implement a modal window that prompts the user to confirm the deletion of an object. My progress code is attached below. Although I h ...

Receive an AJAX HTTP POST request and process it on the backend using Java

In the process of creating a ticketing system using JavaScript/Angular for the frontend, and sending HTTP requests with AJAX. Currently, we are including parameters in the header as shown below: numbPass: 3 Total Price: 39 These details belong to one ...

Obtaining a UTC datetime value in BSON format using Node.js or JavaScript

I'm encountering an issue while attempting to save an entry in a MongoDB time series collection. The problem arises when storing the timeField, resulting in an error thrown by mongo. MongoServerError: 'blockTime' must be present and contain ...

Ways to create a clickable image without any hovering disruptions

I'm currently working on my first website using CSS3, HTML, and JS. Once I finish this version, I plan to switch to bootstrap after ironing out the bugs. However, I've hit a roadblock and could use some help. Here is the js fiddle link: https:// ...

Protractor quickly launches and closes the Chrome browser without completing the entire scenario

In order to test my application using protractor, I created a scenario. The application begins with a non-angular login page and then progresses to an angular page after logging in. Here is the javascript code snippet that was utilized: var chai = requir ...

Sending a post request from a Flutter client to a Node.js Express API

Being new to this platform, I apologize in advance for any beginner mistakes. I am currently working on creating an API with Firebase Cloud Functions using Express.js. My goal is to establish communication between Flutter and this API for user signup. Test ...

Is it possible to achieve a seamless change using show/hide jQuery functions when hovering over an

How can I achieve smooth transitions when using an image map to show a div on hover, similar to the functionality seen on this website: ? Below is my current JavaScript code: var mapObject = { hover : function(area, event) { var id = area.attr ...

Managing Data Forms in JavaScript to Handle Large Amounts of Information

As I dive into learning JavaScript with the goal of creating a large form that remains completely local without involving a web server, I am faced with some challenges. I have extensive experience with PHP, but JavaScript is uncharted territory for me. T ...

"Extract information from a JSON file by reading it and accessing various

I've been working on a Python script to extract data from a JSON file using loops and conditional statements. Here's a snippet of the JSON file: { "count": 3, "result": [ { "type": "first", "first": { ...

I am encountering difficulties in populating a deep subdocument in Mongoose

Here is the updated code snippet that I'm struggling with in terms of model simplification and schema: const guildSchema = new Schema<Guild>({ sheets: [sheetSchema], crews: [crewSchema], }); const GuildModel = getModel('Guild', ...

Is it possible to determine if a JavaScript/jQuery effect or plugin will function on iPhone and iPad without actually owning those devices?

Is there a way to ensure that a javascript/jquery effect or plugin that works well on all desktop browsers will also work on iPhone and iPad without actually owning those devices? Can I rely on testing it on the latest Safari for Windows to guarantee comp ...

Having trouble getting the templateUrl to work properly with AngularUI-Router?

Can you please explain the flow of how a URL is processed when visited and provide insights on why Angular's templateUrl may not be working? When a user clicks on a URL in their browser, it first checks the cache to see if the URL is saved from the $ ...

Encountered an error when attempting to run npm start due to the absence of the required module 'minizlib

I recently cloned a react-native project from GitHub to start working on it, but encountered an issue with npm start failing and displaying the following error: Error: Cannot find module 'minizlib' Require stack: - /usr/local/lib/node_modules/ex ...

Inspecting input parameters for mistakes in gulpfile with yargs

I've been working on an Angular app gulpfile and I'm facing a challenge in catching errors related to the arguments. var gulp = require('gulp'); var args = require('yargs').argv; ... var isProduction = args.env === 'prod ...