Missing Content-Type header in AngularJS request

Utilizing the CORS protocol, the code below effectively sends a request and receives a response. The objective is to modify the content-type header from 'application/x-www-form-urlencoded' to 'application/json'. However, upon making this change, the request fails. Interestingly, when inspecting the request in the browser, it becomes apparent that instead of altering the content-type header, it has actually been entirely removed.

var servicesApp = angular.module('services', [])

    .config(function($httpProvider){

        /* Enable CORS */
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
})


.factory('model', function($http) {

        var testJSON = '{"employees": [ {"firstName":"John", "lastName":"Doe"} ] }';

        $http({
            url: 'http://127.0.0.1:8081/controller/UIController',
            method: "POST",
            params: {"path" : "save"},
            data: "message= " + testJSON,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}

        }).success(function (data, status, headers, config) {
            alert(data.ExampleForm[1]);

        }).error(function (data, status, headers, config) {
            alert(status);
        });

Request From Code Above

Request URL:http://127.0.0.1:8081/controller/UIController?path=save

Request Method:POST

Status Code:200 OK

Request Headersview source

Accept:application/json, text/plain, */*

Accept-Encoding:gzip,deflate,sdch

Accept-Language:en-GB,en-US;q=0.8,en;q=0.6

Connection:keep-alive

Content-Length:67

Content-Type:application/x-www-form-urlencoded

Host:127.0.0.1:8081

Origin:http://127.0.0.1:8020

Referer:http://127.0.0.1:8020/TwineClient/src/index.html

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36

Query String Parametersview sourceview URL encoded

path:save

Form Dataview sourceview URL encoded

message: {"employees": [ {"firstName":"John", "lastName":"Doe"} ] }

Response Headersview source

Access-Control-Allow-Headers:Content-Type

Access-Control-Allow-Methods:POST

Access-Control-Allow-Origin:*

Content-Length:51

Content-Type:application/json;charset=ISO-8859-1

Date:Tue, 11 Feb 2014 16:15:00 GMT

Server:Apache-Coyote/1.1

Replacing 'application/x-www-form-urlencoded' with 'application/json' results in:

Request URL:http://127.0.0.1:8081/controller/UIController?path=save

Request Method:OPTIONS

Status Code:200 OK

Request Headersview source

Accept:*/*

Accept-Encoding:gzip,deflate,sdch

Accept-Language:en-GB,en-US;q=0.8,en;q=0.6

Access-Control-Request-Headers:accept, content-type

Access-Control-Request-Method:POST

Connection:keep-alive

Host:127.0.0.1:8081

Origin:http://127.0.0.1:8020

Referer:http://127.0.0.1:8020/TwineClient/src/index.html

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36

Query String Parametersview sourceview URL encoded

path:save

Response Headersview source

Allow:GET, HEAD, POST, TRACE, OPTIONS

Content-Length:0

Date:Tue, 11 Feb 2014 16:11:02 GMT

Server:Apache-Coyote/1.1

Answer №1

When you change the content-type to application/json, the browser initiates a preflight (OPTIONS) request as per the CORS spec. It is crucial for your server to acknowledge this preflight in order to successfully use application/json as your request content-type. For more information on CORS, check out: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS.

If you have further questions, you can refer to my answer on a related topic on SO here: WebAPI 2 - CORS not working with contentType application/json.

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 operation of my NodeJS application suddenly halts

In my project, I have a Server.js file that I run from the command line using: node server Within the Server.js file, a new instance of class A is created Class A then creates instances of both class B (web socket) and class C (REST API) If the web socket ...

Converting HTML input data to JSON using Client-Side JavaScript

I have a form in my HTML that collects user input, and I want to convert the form data into JSON using client-side Javascript. Check out the code update below~ If the params information is accurate, how can I use JavaScript to post to the API? UPDATE: ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

JavaScript encountered an abrupt cessation of input, catching us off guard

Can someone please help me identify the issue with the JavaScript code below? I encountered an error message stating "Unexpected end of input", but upon reviewing the code, I couldn't find any apparent errors. All my statements seem to be properly ter ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...

Explore the source code of an iframe hosted on a different domain

How can I access the source code of an iframe from a different domain? <script type="text/javascript"> $(document.getElementById("iFrame")).ready(function(){ var iframe = document.getElementById('iFrame'); var innerDoc = iframe.contentDoc ...

I am confident in my code, but why is eslint throwing an error? How can this be happening?

I have been diving into Vue render functions, and here is my index.js: <script> export default { name:'MyHead', props:{ level:Number }, render(h){ return h('div', [h('h'+this.level,'this is head&ap ...

The new FormData(form) method unexpectedly returns an empty object

In this scenario, I am aiming to retrieve key-value pairs. The form on my page looks like this: <form id="myForm" name="myForm"> <label for="username">Enter name:</label> <input type="text" id="username" name="username"> ...

Using Internet Explorer to watch full-screen HTML 5 videos

I am in the process of developing my own HTML 5 Browser Player. Everything seems to be working well, except for getting the full screen feature to function properly in IE 10. Chrome, Safari, and Firefox are all doing great with it. Unfortunately, my JavaS ...

Finding the number of ways to extract arrays with 7 elements from a larger array of 49 elements in Javascript

I have a task to create unique groups of 7 elements from an array of 49 and determine the number of possible outputs. For example: [A,a,B,b,C,c,D,d,E,e,F,f,G,g,H,h,I,i,J,j,K,k,L,l,M,m,N,n,O,o,P,p,Q,q,R,r,S,s,T,t,U,u,V,v,W,w,X,x,Y] The desired outputs are ...

Maximizing the potential of md-order-by attribute to organize date columns within an md-data-table

I'm attempting to implement column sorting in an AngularJS md-data-table for a column containing dates. These dates are formatted as strings DD / MM / YYYY, but I'm struggling to get them sorted correctly. I've tried calling a function that ...

Exploring the concept of iteration in AngularJS

I'm currently working on a project using angular js in conjunction with python flask, and I've encountered an issue while trying to iterate through JSON data in a particular scenario. The situation is outlined below: The JSON data is as follows: ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

What is the best way to remove an item from an array inside another object in JavaScript?

I am currently developing an application using Node, mongoose, and express. My goal is to remove an object from an array that is nested inside another object. Here is the structure of the objects: const oldSection = { _id: '62d3f1d221aa21a03fe3bc21& ...

Can spreading be used for destructuring?

These were the initial props I attempted to pass to a component: const allprops = { mainprops:{mainprops}, // object pageid:{pageId}, // variable setpageid:{setPageId}, // state function makerefresh:{makeRefresh} // state function } <Na ...

Modify the style of a newly created div by clicking on it

Exploring vue-cli and encountering a challenge. I've created a row of 24 div elements with the following code: <template> <div class="row"> <div class="hour" v-on:click="colorize" v-for="n in 24"></div> </div&g ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

What is the best way to reduce the size of a Base64/Binary image in Angular6

I utilized the Ngx-Webcam tool to capture images from my camera. My goal is to obtain both high quality and low quality images from the camera. Although this library provides me with Base64 images, it offers an option to reduce the size using imageQuality ...

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...