问题
Using plain JavaScript AJAX in a browser, can I get the raw HTTP response from the server?
By that I mean headers and body as raw text like:
< HTTP/1.1 301 Moved Permanently
< Location: http://www.google.co.uk/
< Content-Type: text/html; charset=UTF-8
< Server: gws
< Content-Length: 221
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Age: 11
< Date: Mon, 04 Jun 2018 09:12:14 GMT
< Expires: Wed, 04 Jul 2018 09:12:14 GMT
< Cache-Control: public, max-age=2592000
< Connection: keep-alive
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
(NB: I'm not talking about cross-origin requests)
回答1:
You will need to combine two calls to get the body and the response headers.
- To get the headers, use getAllResponseHeaders
- To get the body, use property .response when the readystate is 4 (=DONE)
var request = new XMLHttpRequest();
request.open("GET", "http://www.example.com", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4){
console.log(request.getAllResponseHeaders());
console.log(request.responseText);
}
};
来源:https://stackoverflow.com/questions/50677103/get-raw-http-response-from-ajax