2

I have this mootools request:

new Request({
    url: 'http://localhost:8080/list',
    method: 'get',
}).send();

and a small python server that handles it with this:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import subprocess

class HttpHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/list':
            self.list()
        else:
            self._404()

    def list(self):
        self.response200()
        res = "some string"

        self.wfile.write(res)

    def _404(self):
        self.response404()
        self.wfile.write("404\n")

    def response200(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Headers', 'X-Request, X-Requested-With')
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def response404(self):
        self.send_response(404)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

def main():
    try:
        server = HTTPServer(('', 8080), HttpHandler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

if __name__ == '__main__':
    main()

When I attempt to make this request, I get these errors:

OPTIONS http://localhost:8080/ 501 (Unsupported method ('OPTIONS'))
XMLHttpRequest cannot load http://localhost:8080/. Origin null is not allowed by Access-Control-Allow-Origin.

I'm not sure what's going on. Can someone help me out??

gregghz
  • 3,925
  • 7
  • 40
  • 69

1 Answers1

5

exactly as the response string tells you: OPTIONS http://localhost:8080/ 501 (Unsupported method ('OPTIONS'))

When javascript attempts to request a resource from another origin, modern browsers first ask the other server, the target, if it is ok to make that request from another origin, that's exactly what the Access-Control* headers do. but this request does not happen in a normal GET, since that would be actually performing the request anyway, and instead use the OPTIONS method, which exists for the sole reason to inform clients what they are allowed to do, without actually doing it.

So, you need a do_OPTIONS method, which might look something like:

def do_OPTIONS(self):
    if self.path in ('*', '/list'):
        self.send_response(200)
        self.send_header('Allow', 'GET, OPTIONS')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Headers', 'X-Request, X-Requested-With')
    else:
        self.send_response(404)
    self.send_header('Content-Length', '0')
    self.end_headers()
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304