简体   繁体   English

以编程方式在JavaScript中为Content-Type设置http请求标头

[英]Programmatically setting http request headers in javascript for Content-Type

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. 我的问题是,是否可以按照我的代码示例下面的方式默认类似“ Content-Type”的内容,然后将其覆盖,还是我需要检查正在发送的自定义标头,如果未设置Content-type,则将其设置为默认值。 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. 我可能在“标头”对象中发送了类似JSON的其他“ Content-Type”。 If I do setRequestHeader on Content-Type again does it overwrite or does it send 2 content-type headers in the post request? 如果我再次对Content-Type执行setRequestHeader,它会覆盖还是在发布请求中发送2个Content-Type标头?

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. 编辑 :我不知道为什么我在StackOverflow上问这个问题,我只是意识到我可以通过使用表单处理程序记录我的标头来测试这个问题,我不打算这样做,我还是会把这个问题搁置一旁。

According to MDN : 根据MDN

Sets the value of an HTTP request header. 设置HTTP请求标头的值。 You must call setRequestHeader()after open(), but before send(). 您必须在open()之后但send()之前调用setRequestHeader()。 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: 因此,多次调用setRequestHeader()将产生以下结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM