XMLHttpRequest 无法在后端使用 angular $resource 或 python/cgi 脚本加载 http://host1:5000/path

XMLHttpRequest cannot load http://host1:5000/path using angular $resource front end or python/cgi script in backend

XMLHttpRequest 无法加载 http://host1:5000/endpoint. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://originhost:3000' 因此不允许访问。

如何从前端或服务器端(Python CGI 脚本)使用 anguarjs 解决这个问题。我无权更改浏览器、crome 或安全性的任何内容,甚至无法根据请求进行更改。

Angular代码前端:

function scheduleReportServiceFactory($resource){
  var schedule_report_url = 'http://host1/endpoint:bucket';
  var auth = btoa("xyz:xyz");
  var headers = {
   "Authorization" : "Basic " + auth,
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': 'http://originhost:3000'
  };
  return {
   schedule_report : $resource(schedule_report_url, {}, {
    query : {
     method : 'GET',
     params : {
      bucket : '@bucket'
     },
     headers: headers,
     cache : true,
    }
   })
  };
 
 }
Python 代码后端:
import .....


class Dispatcher(object):

    def not_found(self, environ, start_response):
        start_response('404 Not Found', [('Content-Type', 'application/octet-stream')])
        return []

    def __init__(self, mounts=None):
        self.mounts = mounts or {}

    def __call__(self, environ, start_response):
        script = environ.get('PATH_INFO', '')
        while '/' in script:
            if script in self.mounts:
                app = self.mounts[script]
                break
            script, last_item = script.rsplit('/', 1)
        else:
            app = self.mounts.get(script, self.not_found)
        return app(environ, start_response)

print >> sys.stderr, "app.cgi: server starting", os.environ.get('PATH_INFO')
for k in os.environ:
   print >>sys.stderr, k, os.environ[k]

app = Dispatcher({
   '/xyz/report/v1': report_app(),
   '/xyz/replication/v1': dr_app(),
})
if __name__ == '__main__':
    os.environ['DEBUG'] = '1'
    from werkzeug.serving import run_simple
    run_simple('0.0.0.0', 5000, app, use_debugger=True, use_reloader=True)
else:
    CGIHandler().run(app)

更多信息:

-sh-4.2$ curl -u xyz -H "Origin originhost:3000" --verbose   localhost:5000/endpoint/xyz
Enter host password for user 'xyz':
* About to connect() to localhost port 5000 (#0)
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
* Server auth using Basic with user 'xyz'
> GET /endpoint/xyz HTTP/1.1
> Authorization: Basic emt5ajM0aTowNjZCZXg0MjU=
> User-Agent: curl/7.29.0
> Host: localhost:5000
> Accept: */*
> Origin originhost:3000
>
* HTTP 1.0, assume close after body
< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: application/octet-stream
* Authentication problem. Ignoring this.
< WWW-Authenticate: Basic
< Content-Length: 0
< Server: Werkzeug/0.12.2 Python/2.7.5
< Date: Mon, 24 Jul 2017 18:22:26 GMT
<
* Closing connection 0


-sh-4.2$ curl -u xyz -H "Origin originhost:3000"   -H "Access-Control-Request-Method: GET"   -H "Access-Control-Request-Headers: X-Requested-With"   -X OPTIONS --verbose   localhost:5000/endpiont/xyz
Enter host password for user 'xyz':
* About to connect() to localhost port 5000 (#0)
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 5000 (#0)
* Server auth using Basic with user 'xyz'
> OPTIONS endpoint/xyz HTTP/1.1
> Authorization: Basic emt5ajM0afhtTowNjZCZXg0Mg==
> User-Agent: curl/7.29.0
> Host: localhost:5000
> Accept: */*
> Origin originhost:3000
> Access-Control-Request-Method: GET
> Access-Control-Request-Headers: X-Requested-With
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: text/html; charset=utf-8
< Allow: HEAD, GET, POST, OPTIONS, DELETE
< Content-Length: 0
< Server: Werkzeug/0.12.2 Python/2.7.5
< Date: Mon, 24 Jul 2017 18:24:53 GMT
<
* Closing connection 0

我认为您的问题不在前端,而是在服务器端。这是一个 CORS 问题。您需要在服务器上允许后端从您的前端获取请求。 ..

我不知道如何在 Python 中做到这一点,但基本上在所有语言中都是可能的