是否可以使用 javascript 更改 http 请求的标头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11214718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:56:41  来源:igfitidea点击:

Is it possible to alter http request's header using javascript?

javascriptjqueryajaxhttp

提问by thiagocfb

Is it possible to use some kind of JavaScript to change or set a HTTP request's header?

是否可以使用某种 JavaScript 来更改或设置 HTTP 请求的标头?

回答by zamnuts

Headers are passed long before javascript is downloaded, let alone interpreted. The short is answer is no.

标头在 javascript 下载之前很久就被传递了,更不用说解释了。答案是否定的。

However, if you're speaking in the context of an ajax call (let's use jQuery as an example), the request headers can be written.

但是,如果您是在 ajax 调用的上下文中说话(让我们以 jQuery 为例),则可以编写请求标头。

See reading headers from an AJAX call with jQuery. See setting headers before making the AJAX call with jQuery

请参阅使用 jQuery 从 AJAX 调用中读取标头在使用 jQuery 进行 AJAX 调用之前,请参阅设置标头

However, if your javascript is server-side (e.g. node.js) that would be a yes (probably not since the post mentions HTML):

但是,如果您的 javascript 是服务器端(例如 node.js),那将是肯定的(可能不是因为帖子提到了 HTML):

var body = 'hello world';
response.writeHead(200, {'Content-Length': body.length,'Content-Type': 'text/plain' });

回答by Greg

Using the XMLHttpRequest object, you can use the setRequestHeaderfunction.

使用 XMLHttpRequest 对象,您可以使用该setRequestHeader函数。

A little code to get you on your way:

一个让你上路的小代码:

var xhr = new XMLHttpRequest()
xhr.open("GET", "/test.html", true);
xhr.setRequestHeader("Content-type", "text/html");

xhr.send();

The method setRequestHeadermustbe called after open, and before send.

该方法setRequestHeader必须在打开之后和发送之前调用。

More info: https://developer.mozilla.org/en/DOM/XMLHttpRequest#setRequestHeader()

更多信息:https: //developer.mozilla.org/en/DOM/XMLHttpRequest#setRequestHeader()