What is the best way to set multiple headers and change the content type when needed?

I am struggling with a function that cannot be overridden:

  getHtml:function(aURL,aPostData,aHeaders,aMethod){
    this.xhr = new XMLHttpRequest();
    var tmp=this;
    this.xhr.onreadystatechange=function(){
      tmp.onStateChange();
    };
    if(aPostData||aPostData==""){
      this.xhr.open(aMethod?aMethod:"POST", aURL, true);
      this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }else this.xhr.open(aMethod?aMethod:"GET", aURL, true);
    if(aHeaders){
      for(var t in aHeaders){
        this.xhr.setRequestHeader(t,aHeaders[t]);
      }
    }
    try{
      this.xhr.send(aPostData);
    }catch(e){
      this.doNext("");
    }
  }

What is the correct way to pass multiple headers (aHeaders) to this function? If I include Content-Type as a header, will it replace the default value (

application/x-www-form-urlencoded
)?

I need to pass two headers:

  1. x-myheader-value: zzz1111bbb
  2. content-type: application/javascript

Answer №1

Your function seems to be expecting an object structure like this:

var headers = {
    "x-myheader-value": "zzz1111bbb",
    "Content-Type": "application/javascript"
};
...
getHtml( ... , headers, ...);

It's worth noting that if you set the same header multiple times, the expected behavior is for the values to be concatenated rather than replaced... For more information, refer to the W3C specs or MDN. Therefore, in your situation, passing the Content-Type header while also passing a non-empty aPostData object will result in an incorrect header value.

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

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

The switch statement remains unchanged for varying variables

Here is some code that I am working with: updateTable(selectedIndex) { console.log("running updateTable function"); let level = ''; // if (selectedIndex == 1){ // this.setState({level: 'day'}) // th ...

Issue with create-react-app and express server not displaying correctly in Internet Explorer

My application functions perfectly with Chrome and Safari. It utilizes React for the front-end and Express for the back-end. However, when I try to open it in Internet Explorer, all I see is a blank white page. Additionally, I encounter this error message: ...

Locating characters within an array of Charactes

For an assignment, I am tasked with identifying substrings within an array. Here is the array provided: char DNA[] = {'A', 'G', 'C', 'G', 'G', 'G', 'A', 'C', 'C', & ...

Verify if an Ajax request has been made

I've been trying to figure out how to determine if a request is made via AJAX in C#, but I'm having trouble getting it to work. Below is the code I'm using. I am using a method to make an AJAX call on the client side (I'm using the Acti ...

What is the best way to change an array of strings into a single string in JavaScript?

I am working with a JavaScript array that contains strings arranged in a specific format: arrayOfString = ['a', 'b,c', 'd,e', 'f']; My goal is to transform this array into a new format like so: myString = ["a", "b ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

HTML Error: The result is unspecified

I have written a function that is supposed to return 105; 6.5 and 110; 4.5, but instead it returns undefined: undefinedundefined: undefined. Can someone please advise me on what changes I need to make to get the correct results? I have heard about asynchro ...

Having trouble initializing an array of objects to store data in MongoDB using AngularJS

I am facing an issue while trying to save dynamically created HTML in MongoDB using Mongoose from AngularJS. The problem lies in creating the required object that matches the Mongoose schema I have defined. model code var SegmentSchema = new Schema({ n ...

Organizing an array of objects within MUI cards based on social media platforms

I'm currently developing an application that showcases athlete data in a grid layout using MUI Grid. The colored borders on the left side of each card are determined by the corresponding social network associated with that athlete. https://i.sstatic. ...

Using Console.log() will display 'undefined' prior to receiving any data

I am facing a problem with a lifecycle hook that I have been trying to troubleshoot. export default class EditRevision extends Component { state = { data: [], customColumns: [] } componentWillMount = () => { axios.get('http:/ ...

Issues with Ajax response being added to the table

I am encountering a technical problem with my university project. The task assigned by the professor is as follows: We need to create a static table that lists 3 domain names in order to enhance the performance of the domain availability API. <table&g ...

What is causing the newly generated input tags to disappear from the page?

I'm having an issue where my code successfully creates new input tags based on user input, but they disappear shortly after being generated. What could be causing this to happen? <form> <input type='text' id='input' /> ...

What is the best method for calculating the total sum by multiplying the values in an array?

In my current project, I have an array consisting of multiple objects, each containing a property named "amount". My goal is to sum up all these amount values to get the total. Initially, I attempted to use a for loop but encountered an issue where settin ...

What behavior does the operation x=x[class_id] exhibit when applied to NumPy arrays?

Currently, I am delving into Python and working on a machine learning challenge. class_ids=np.arange(self.x.shape[0]) np.random.shuffle(class_ids) self.x=self.x[class_ids] I'm struggling to comprehend the self.x=self.x[class_ids] line within this Nu ...

Nodemon isn't functioning properly: nodemon isn't loading as expected

db.js const mongoose = require('mongoose'); const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; const connectToMongoDb = ()=>{ mongoose.connect(mongoURI, ()=>{ ...

What could be the reason that a MUI component does not disappear when the display is set to none in the sx prop?

I'm attempting to construct a responsive side drawer using MUI's Drawer component in React, specifically leveraging MUI version 4.12.1. In the example provided on the mui.com website, they utilize the sx prop and pass an object with different di ...

Revamping MapReduce in MongoDB Version 2.4

After upgrading to MongoDB 2.4, I encountered an issue with a map function that uses db, as mentioned in the release notes. The release notes suggest refactoring, but I am unsure about the best approach to take. The part of the function that is no longer ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

Prevent clicking on a specific column in a table using Jquery

Attempting to utilize Jquery for clicking on a table row in order to navigate to a new page. However, encountering an issue with the last column containing a button that redirects to a new page when clicked on the edge. Is there a way to disable the oncl ...