1

I'm writing some code to handle sending post data for my application and I wanted to make it so that I can send custom headers from another function if I need them. My question is, can I default something like "Content-Type" the way my code example does below and then overwrite it, or do I need to check the custom headers being sent, and if Content-type is not set, set it to the default. Basically, during the creation of the post request, can you overwrite headers programmatically?

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", formData.length);    
// check for custom headers
if ((headers !== null) && (headers !== undefined)) {
    for(var k in headers) {
        if(headers.hasOwnProperty(k) {
            xmlhttp.setRequestHeader(k.toString(), headers[k]);
        }
    }
}

I'm sending a different "Content-Type" like JSON perhaps in the "headers" object. If I do setRequestHeader on Content-Type again does it overwrite or does it send 2 content-type headers in the post request?

edit: I don't know why I asked this on StackOverflow, I just realized I could probably test this by logging my headers with a form handler, which I'm off to do, I'll leave the question up anyway.

3
  • Be careful with for..in loops and not using hasOwnProperty Commented Aug 3, 2015 at 19:31
  • @AlexW I'm really not clean on what that does still even after reading about it, but I added to my loop. Commented Aug 3, 2015 at 19:47
  • 1
    It prevents unnecessary iterations over properties in an object's prototype chain. Most of the time you don't want to iterate over the prototype properties. Commented Aug 3, 2015 at 19:49

1 Answer 1

3

According to MDN:

Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send(). If this method is called several times with the same header, the values are merged into one single request header.

So calling setRequestHeader() multiple times will yield the following:

Content-Type: application/x-www-form-urlencoded, application/json
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I just tested this like I put in my question with a curl request and a php script to log headers.. it does exactly that. My assumptions were double wrong, it neither overwrites or sends two but merges. So I guess if I want default headers in my function I need to check the headers being sent first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.