简体   繁体   English

如何在 JavaScript 中提取自定义 HTTP POST 请求 header 以便在另一个 POST 请求中传输?

[英]How can I extract a custom HTTP POST request header in JavaScript for it to be transmitted in another POST request?

I'm wanting to extract a custom HTTP request header from a POST request using Javascript for it to be used in a request later.我想使用 Javascript 从POST请求中提取自定义 HTTP请求header 以便稍后在请求中使用。 The reason why this needs to be a POST request is that this custom header is only incorporated on the POST HTTP method, and not GET or other HTTP verbs.这需要一个POST请求的原因是这个自定义 header 仅包含在POST HTTP 方法中,而不是GET或其他 HTTP 动词。

Let's say the custom HTTP POST request header is X-CUSTOM-TOKEN .假设自定义 HTTP POST请求 header 是X-CUSTOM-TOKEN How can I read and extract the value of X-CUSTOM-TOKEN from POST / before submitting it alongside the following (HTTP Form):在将 X-CUSTOM-TOKEN 的值与以下内容(HTTP 表单)一起提交之前,如何从POST /中读取和提取X-CUSTOM-TOKEN的值:

history.pushState('', '', '/');
document.body.innerHTML='<html><body style="background-color:black;"><form id="foobar" action="https://localhost:4449/" method="POST" enctype="multipart/form-data"><input type="hidden" name="access" value="true" /><input type="submit" value="Submit request" /></form></body></html>';
document.getElementById('foobar').submit();

I know this use-case sounds dumb, but it's for educational purposes where I can better understand JavaScript pertaining to HTTP transmission.我知道这个用例听起来很愚蠢,但出于教育目的,我可以更好地理解与 HTTP 传输有关的 JavaScript。

Your help is much appreciated.非常感谢您的帮助。

It depends.这取决于。

If the request was constructed using the Fetch API, then you can interrogate the request object for its headers.如果请求是使用 Fetch API 构造的,那么您可以查询请求 object的标头。

But if the request was constructed using XMLHTTPRequest, there does not appear to be any way to obtain the headers from the prepared-but-unsent request.但是,如果请求是使用 XMLHTTPRequest 构造的,则似乎没有任何方法可以从准备但未发送的请求中获取标头。 Of course, if the code is yours, you should have access to the values when you configure the XHR, and so you can use that opportunity to store the data somewhere that it can be retrieved later.当然,如果代码是你的,你应该可以在配置 XHR 时访问这些值,这样你就可以利用这个机会将数据存储在以后可以检索到的地方。

You're out of luck if the XHR is constructed by third-party code that you cannot edit.如果 XHR 是由您无法编辑的第三方代码构建的,那么您就不走运了。 In that case, you could use some kind of server-side proxy to echo the data back to you.在这种情况下,您可以使用某种服务器端代理将数据回显给您。 That would not be unusual in an educational setting.这在教育环境中并不少见。

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

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