Created
August 14, 2020 18:48
-
-
Save Bradan/d038fb72e1501fc1359d1e5360c45540 to your computer and use it in GitHub Desktop.
Problem with CORS and fetch on same origin. Browser assumes the "same-origin" to be null, but why?
This file contains 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 | |
from http.server import HTTPServer, HTTPStatus, SimpleHTTPRequestHandler, test | |
import sys | |
from urllib.parse import urlparse | |
import os | |
class TestRequestHandler (SimpleHTTPRequestHandler): | |
def do_GET(self): | |
"""Serve a GET request.""" | |
url = urlparse(self.path) | |
if url.path == '/' or url.path == '/index.html': # index.html | |
f = self.send_head('text/html') | |
self.wfile.write('''<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Test</title> | |
<script type="text/javascript" src="control.js"></script> | |
</head> | |
<body> | |
</body> | |
</html>'''.encode('utf-8')) | |
elif url.path == '/control.js': # control.js will try to fetch the fetch.xml | |
f = self.send_head('application/javascript') | |
self.wfile.write('''function init() { | |
fetch("fetch.xml").then(r => r.text()).then(t => console.log(t)); | |
} | |
window.addEventListener("load", init);'''.encode('utf-8')) | |
elif url.path == '/fetch.xml': # fetch.xml | |
f = self.send_head('text/xml') | |
self.wfile.write('''<?xml version="1.0" encoding="UTF-8"?> | |
<root> | |
<test>Hi</test> | |
</root>'''.encode('utf-8')) | |
def send_head(self, ctype): | |
self.send_response(HTTPStatus.OK) | |
self.send_header('Content-Type', ctype) | |
self.send_header('Access-Control-Allow-Origin', 'http://127.0.0.1:8000') | |
self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') | |
self.send_header('Access-Control-Max-Age', 86400) | |
self.send_header('Referrer-Policy', 'no-referrer-when-downgrade') | |
self.send_header('Content-Security-Policy', 'sandbox allow-scripts') | |
SimpleHTTPRequestHandler.end_headers(self) | |
if __name__ == '__main__': | |
test(TestRequestHandler, HTTPServer, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment