【问题标题】:Can't remove CORS error even so I included all headers即使我包含了所有标题也无法删除 CORS 错误
【发布时间】:2021-04-13 03:22:14
【问题描述】:

我正在使用 js 客户端和服务器端 (python) 编写简单的网站,我尽一切努力消除 CORS 错误,但没有任何效果。我为此编写了所有需要的标题,但仍然出现此错误。所以网站应该向服务器发送请求并获得答案。 错误:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我的文件.html:

<!DOCTYPE html>
<html>
<head>
    <title>requestJs</title>
</head>
<body>
<button class="myButton">SEND</button>
<script type="text/javascript">
let theButton = document.querySelector(".myButton");
    theButton.addEventListener('click',function() {
  const xhr = new XMLHttpRequest();

xhr.onload = function() {
 alert(`Статус: ${xhr.status}; Результат: ${xhr.response}`)
};

xhr.onerror = function() {
  alert('Ошибка запроса');
};

xhr.open("GET", "http://127.0.0.1:8000/", true);
xhr.send(2);
    })

</script>
</body>
</html>

服务器端:

import http.server as httpserver


class CORSHTTPRequestHandler(httpserver.SimpleHTTPRequestHandler):
    def send_head(self):
        """Common code for GET and HEAD commands.
        This sends the response code and MIME headers.
        Return value is either a file object (which has to be copied
        to the outputfile by the caller unless the command was HEAD,
        and must be closed by the caller under all circumstances), or
        None, in which case the caller has nothing further to do.
        """
        path = self.translate_path(self.path)
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # redirect browser - doing basically what apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                self.end_headers()
                return None
            for index in "index.html", "index.html":
                index = os.path.join(path, index)
                if os.path.exists(index):
                    path = index
                    break
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.send_header("Access-Control-Allow-Origin:", "*")
        self.send_header("Access-Control-Allow-Methods:", "GET,HEAD,PUT,PATCH,POST,DELETE")
        self.send_header("Access-Control-Allow-Headers:", "Content-Type, Access-Control-Allow-Origin, xxx")
        self.end_headers()
        return f


if __name__ == "__main__":
    import os
    import socketserver

    import sys

    PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000

    handler = CORSHTTPRequestHandler

    httpd = socketserver.TCPServer(("", PORT), handler)

    print(f"serving at port {PORT}")
    httpd.serve_forever()

请帮帮我,我的问题是什么?

【问题讨论】:

  • 你检查过为什么你的网站的来源是null吗?您能否确认响应包含您设置的所有标头?
  • 你确定self.send_header("Access-Control-Allow-Origin:", "*")不应该是self.send_header("Access-Control-Allow-Origin", "*")吗?
  • @acincognito 我按照你的说法更改了标题,但我不明白这个关于 origin: null 的事情,你能解释一下这是什么意思以及我应该添加哪些标题?我必须在js请求中添加标头吗?
  • Access-Control-Allow-Headers。我想知道你是否应该指定这个。
  • @Booboo 谢谢你会读到的。顺便说一句,有没有办法根本不面对cors?因为我不认为每个网站都这样做。我猜他们出现是有特殊原因的

标签: javascript python ajax cors


【解决方案1】:

这不是一个全面的答案,但它可能会有所帮助。

CORS 完全是一种浏览器功能。您可以在浏览器中将其关闭。因此,我建议第一步是启动一个无 CORS 的浏览器来测试您的应用程序。确保不要在此浏览器会话中打开您的银行页面,这不安全!

google-chrome --user-data-dir=/var/tmp/Chrome --disable-web-security

如果一切正常,那么问题只是 CORS。 如果你只在开发环境中运行,你甚至可以每次都这样做。 如果您在生产环境中运行,最简单的选择通常就是使用为您修复这些内容的网关。我就是这样开始工作的。

如果上述内容还不够好并且您想调试,请记住所有浏览器 CORS 请求都是由预检 OPTIONS 请求发起的。有时这就是问题所在。确保您的服务器能够处理和响应 OPTIONS,并检查它是否正确响应。

【讨论】:

  • 感谢您的回答,但如果我在浏览器上关闭 CORS,它可能会起作用,但仅限于我!但是我不是唯一会使用这个网站的人,所以我的客户将无法从服务器收到答案?
  • 这就是为什么我说你需要另一个生产解决方案!对我来说,我使用了 krakend 网关 API,它使所有的 CORS 东西都能正常工作。
  • 但是怎么可能正常解决呢?我的意思是普通的大网站如何解决这个问题?我没想到发送简单请求会遇到这么多问题,尤其是在 localhost
  • 大网站肯定会使用 API 网关。小型站点根本不需要 CORS,因为它们只有一个来源。您已经构建了一个具有两个来源的系统,因此您已经开始研究编排/负载平衡/请求转发等。可以手动处理标头以使其正常工作,但正如我所说,我不知道怎么做。添加赏金并希望其他人知道。但是手动争吵标头不会扩展。如果您的网站永远不需要扩展,请考虑采用单体架构并避免这些问题。如果是,请获取网关。
  • 我也不认为我第一次尝试微服务时会遇到所有这些问题。不过,问题不是请求或本地主机。您可以从 CURL 或 Postman 发送完全相同的请求并且没有问题。是浏览器中来自 Javascript 的 ajax 调用导致了这些问题。如果您想了解历史,请查看 JSONP。
猜你喜欢
  • 2019-12-13
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 2022-01-18
  • 2015-02-17
  • 2021-12-06
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多