Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually:

Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string.

var request = new XMLHttpRequest();
try{
    request.open("POST", url);
    request.setRequestHeader('Accept', 'application/json');
    request.send(jsonString);
} catch(e) {
    alert(e);
}

and

var options = {
    type: "POST",
    url: url,
    dataType: "json",
    data: jsonString,
    accept: "application/json"
};

$.ajax(options)

The issue we are facing is that the platform to which we are posting requires a header Content-Type with the value of "application/json".

As it stands currently, in the first method, when

request.setRequestHeader('Content-Type', 'application/json')
; is added 1 line above or below the Accept header, the method changes to OPTIONS, the Accept header becomes "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8", and the Content-Type vanishes as if it was not recognized.

Similarly, in the second method, adding contentType: "application/json" anywhere within the options results in the same issue encountered in the first example.

What would be the correct way to set a Content-Type header in ajax or XMLHttpRequest?

Edit: It is worth mentioning that using the Firefox REST client plugin, everything - including the json string, URL, accept and content-type headers - works flawlessly. However, we are unable to set the content header on our own page.

Answer №1

If you add request.setRequestHeader('Content-Type', 'application/json'); either one line above or below the Accept header in the first example, the method used will switch to OPTIONS.

This change occurs because you are sending a cross-origin request from JavaScript embedded in a webpage. Modifying the content-type (to one that can't be created with a simple HTML form) triggers a preflight request, which seeks permission from the server to proceed with the actual request.

To resolve this issue, the server must be configured to respond with appropriate CORS headers granting permission:

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Access-Control-Allow-Origin: http://your.site.example.com
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type

After these adjustments, the browser will execute the POST request as intended.

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

ExpressJS route encountering issues with GET method functionality

I'm facing an issue with my code where the function is not running inside the specific routing when trying to retrieve data using /:user. Can someone help me identify the mistake in the following implementation? const express = requi ...

What could be causing the error when trying to submit to OData Edm.Decimal type?

Having an issue submitting JSON to an OData service. The $metadata indicates it expects this format: <Property Name="curClaimValue" Type="Edm.Decimal" Nullable="true" Precision="19" Scale="4"/> This snippet is from my JSON data: ..."curClaimValue" ...

Populate DataTable with HTML content by fetching it through Ajax requests

My goal is to dynamically load the HTML returned from a controller into a div when a user clicks on a row in a table. Check out my code snippet below: // Add event listener for opening and closing details jQuery('#exRowTable tbody').on ...

What are the steps to connect to, fetch, save, and remove files from a remote file server using Node.js?

Currently working on a project in node.js that requires saving an uploaded file from a client onto a remote file server for later retrieval. While I'm familiar with accessing and storing files on the local file system using 'fs', I am unsure ...

Condition has been fulfilled for both ngShow and ngHide

I am attempting to show a loading icon while data is being loaded, and then display the data once it is ready. However, I am encountering a problem where for a brief moment, both the loading icon and the data are visible... Below is my code snippet: $scop ...

Filter out JSON array fields based on specific values

Suppose I need to extract a CSV with specific fields from a large json file produced by an API... all relevant data is contained within an array. jq -r ".array[] | [.uniqV,.V1,.V2,.V3] | @csv" something.json ... but if the unique value begins with a part ...

Encountering issues with the Justify props in Material UI grid – how to troubleshoot and solve the problem

Can someone help me troubleshoot why justify is not working in this code block? <Grid container direction='column' alignItems='center' justify='center' spacing='1'> <Grid item xs={12}> <Ty ...

Struggled to Find a Solution for Code Alignment

Is there a tool or software that can align different types of codes with just one click? I've tried using the Code alignment plugin in Notepad++, but it hasn't been effective. For example, when aligning HTML code using tags, I couldn't find ...

Why do some button clicks not trigger a page refresh in JavaScript?

Hey there, I have a situation where I have two buttons - one to add a dog to the dog list and another to clear the entire list. Both buttons are functioning properly, but I'm having an issue with only the OnSubmit button refreshing the page. The dog ...

What is the process for spawning a terminal instance within a NodeJS child process?

I'm in the process of setting up a discord channel to serve as an SSH terminal. This involves using a NodeJS server to establish the connection. A custom command will then be used to spawn a new terminal instance that can function as a shell. However ...

The orthographic camera in Three.js offers a unique perspective for rendering

Currently, I am working on a project involving an application that showcases various 3D models. The process involves loading the models, creating meshes, and adding them to the scene as part of the standard procedure. Upon completing the addition of the la ...

Achieve a customized glow effect by blending FragColor with UnrealBloom in ThreeJS using GLSL

I am interested in implementing selective bloom for a GLTF model imported into ThreeJS using an Emission map. To accomplish this, the first step is to make objects that should not have bloom completely black. The plan includes utilizing UnrealBloomPass an ...

Sending NodeJS Buffer as form data to Spring Boot in a correct way

I'm facing an issue with my NodeJS application where I am working with an image buffer called qrCode const qrCodeData = Buffer.from(body).toString('base64'); //body received, not sure if base64 is correct f ...

Functions perfectly on Chrome, however, encountering issues on Internet Explorer

Why does the Navigation Bar work in Chrome but not in Internet Explorer? Any insights on this issue? The code functions properly in both Internet Explorer and Chrome when tested locally, but fails to load when inserted into my online website editor. Here ...

Updating the text input value in a database with PHP upon button click

Here is a breakdown of what has been implemented so far: The database table is named adhar_card. Below is the structure image for reference (Adhard_card_id serves as the primary key). https://i.sstatic.net/8j4m6.jpg Clicking on the verify button will cha ...

Unity3D encountering issues running Newtonsoft Json code

I recently made an update to the file loading process in my code: string filename = Path.Combine(Data.BaseDir, "entities.txt"); if (File.Exists(filename)) { string tempJson = System.IO.File.ReadAllText(filename); var settings = new JsonSerializerSet ...

In React Native, I must include individual radio buttons for each item retrieved from the API

When I select a radio button on mobile, all radio buttons get selected instead of just the one clicked. Here is the current behavior: https://i.stack.imgur.com/qRJqV.jpg The expected behavior is to have only the clicked radio button selected, like in thi ...

Ways to establish a default search outcome in a search box

Looking to create a search bar with JavaScript and JSON to display default search results for visitors. Currently, the search bar only shows results after text is removed. How can I show predefined search results when the page is loaded? const search = ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

Is it accurate to categorize every ajax request (using xmlhttprequest) as a web service request?

Recently, I began incorporating AngularJS with Spring MVC as my backend. I have been utilizing $resource to connect with my backend. Given that this is a restful service and $resource operates using ajax, I find myself questioning: 1) Is ajax solely used ...