简体   繁体   中英

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. 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.

Let's say the custom HTTP POST request header is 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):

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.

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.

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. 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.

You're out of luck if the XHR is constructed by third-party code that you cannot edit. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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