自学内容网 自学内容网

【协议】CORS浏览器

今天跟前端对接遇到浏览器CORS问题

保存html丢到浏览器,点击运行

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>跨域请求示例</title>
</head>
<body>
  <h1>跨域请求</h1>
  <button id="fetchData">获取数据</button>
  <p id="result"></p>

  <script>
    document.getElementById('fetchData').addEventListener('click', async () => {
      try {
        // 创建要发送的数据对象
        const requestData = {
          text: "绘制一辆车与美女在中间"  // 填写要请求的文本内容
        };

        // 发送 POST 请求
        const response = await fetch('http://xxx/xxx', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'  // 设置 Content-Type 为 application/json
          },
          body: JSON.stringify(requestData),  // 将数据对象转化为 JSON 字符串
          // Remove 'credentials: "include"' to allow wildcard CORS '*' support
        });

        // 解析 JSON 响应
        if (response.ok) {
          const data = await response.json();
          document.getElementById('result').innerText = data.message;  // 显示返回的消息
        } else {
          console.error('请求失败,状态码:', response.status);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    });
  </script>
</body>
</html>

配置Python CORS处理机制

class prompt(tornado.web.RequestHandler, object):
    executor = ThreadPoolExecutor(50)
    def options(self):
        # 设置跨域相关的响应头,允许跨域的 OPTIONS 请求通过
        self.set_status(204)
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Headers",
                        "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Accept, Set-Cookie, token, x-ca-signature")
        self.set_header("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE, HEAD, PATCH")
        self.finish()

    @gen.coroutine
    def post(self):
        data = {}
        data['returncode'] = "-1"
        data['message'] = "null"
        try:
            self.request.log_str = '('
            try:
                dataJsonStrUni = self.request.body.decode("utf-8")
                post_data = json.loads(dataJsonStrUni)
                logger.info("Post Encoding is UTF-8!")
            except:
                dataJsonStrUni = self.request.body.decode("GB2312")
                post_data = json.loads(dataJsonStrUni)
                logger.info("Post Encoding is GB2312!")
            if "model" in post_data.keys():
                model = int(post_data["model"])
            else:
                model = 0
            if "text" in post_data.keys():
                text = post_data["text"]
            else:
                text = ''
            returncode, result = use_ai(urls[models[model]], text)
            data['returncode'] = returncode
            data['message'] = result
            logger.info(result)
        except Exception as e:
            traceback.print_exc()
            logger.info(e)
            logger.info(e.__traceback__.tb_frame.f_globals["__file__"])
            logger.info(e.__traceback__.tb_lineno)
            # 非法请求
            self.request.log_str += ('request error:' + str(e))
            data['returncode'] = -1
            data['message'] = "null"
            logger.info(str(data['returncode']) + ' ' + data['message'])
        self.request.log_str += (') (' + str(data['returncode']) + ' ' + data['message'] + ') ')
        self.set_header("Content-Type", "application/json;charset=UTF-8")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Headers",
                        "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Accept, Set-Cookie, token, x-ca-signature")
        self.set_header("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE, HEAD, PATCH")

        self.write(tornado.escape.json_encode(data))

    @tornado.gen.coroutine
    def get(self):
        self.set_header('Content-Type', 'application/json')
        self.write("try post")

在这里插入图片描述
解决!


原文地址:https://blog.csdn.net/xi_shui/article/details/143695630

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!