Created
August 10, 2018 16:20
-
-
Save matsub/1e29e44afbb4bce2c6dd98caa9bfc392 to your computer and use it in GitHub Desktop.
a memo of xhr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import time | |
from http.server import ( | |
BaseHTTPRequestHandler, | |
HTTPServer, | |
) | |
WAIT_TIME = 1 # sec | |
class RequestHandler(BaseHTTPRequestHandler): | |
def _set_headers(self): | |
self.send_response(200) | |
self.send_header('Access-Control-Allow-Origin', '*') | |
self.end_headers() | |
def do_GET(self): | |
self._set_headers() | |
time.sleep(WAIT_TIME) | |
self.wfile.write(b"Hello, world!") | |
if __name__ == "__main__": | |
server_address = ('', 8000) | |
httpd = HTTPServer(server_address, RequestHandler) | |
httpd.serve_forever() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
function testxhr() { | |
return new Promise( (resolve, reject) => { | |
const xhr = new XMLHttpRequest(); | |
xhr.timeout = 500 | |
xhr.open("GET", "http://localhost:8000/", true) | |
xhr.onerror = () => { | |
reject(new Error("got onerror")) | |
} | |
xhr.onabort = () => { | |
reject(new Error("got onabort")) | |
} | |
xhr.ontimeout = () => { | |
reject(new Error("got ontimeout")) | |
} | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState !== 4) { | |
console.warn(`xhrstate changed ${xhr.readyState}`) | |
return | |
} | |
if (xhr.status === 0) { | |
reject(new Error(`xhr.status==${xhr.status} & xhr.readyState==${xhr.readyState}`)); | |
return | |
} | |
resolve(xhr.responseText) | |
} | |
xhr.send(null) | |
}); | |
} | |
(async function() { | |
console.log(await testxhr()) | |
})() | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment