首页 > 解决方案 > 通过 chrome 扩展使用 JavaScript 的 Ajax - 错误阻止了 MIME 类型 application/json 的跨域响应

问题描述

在通过 chrome 扩展从 JS 到我的后端“python”的 Ajax 简单数组后,无法得到响应

控制台中出现错误:

Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:5000/test with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details

我试过检查

https://www.chromestatus.com/feature/5629709824032768

https://www.chromium.org/Home/chromium-security/corb-for-developers

我从阅读这两个资源中学到的是为什么他们创建了 CORB 或 CORS,但它并没有提出任何适用于所有开发人员的示例,或者我可能以某种方式迷失在其中,我不是确定我应该做什么或添加到我的代码中

更新:我也试过了

如何阻止 CORB 阻止对以 CORS 标头响应的数据资源的请求?

跨域读阻塞 (CORB)

XMLHttpRequest 无法加载 XXX No 'Access-Control-Allow-Origin' 标头

背景.js

//added this part:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  fetch(request.input, request.init).then(function(response) {
    return response.text().then(function(text) {
      sendResponse([{
        body: text,
        status: response.status,
        statusText: response.statusText,
      }, null]);
    });
  }, function(error) {
    sendResponse([null, error]);
  });
  return true;
});

主要活动:

{
  "manifest_version": 2,
  "name": "testExtention",
  "description": "test extention",

  "browser_action" : {
    "default_title" : "hello computer!",
    "default_popup" : "popup.html"
  },

  "background": {
    "scripts": ["background.js"]
  },
  "content_scripts": [
  {
      "matches": ["https://www.example.com/*", "https://m.example.com/*"],
      "js": ["content.js"]
  }],

  "version": "1.0",
  "permissions": [ "tabs", "storage" ,"http://127.0.0.1:5000/*" ]
}


我的 js Ajax代码:

const req = new XMLHttpRequest();
req.open('POST' , "http://127.0.0.1:5000/test");
// for cors
req.setRequestHeader("dataType",'json');
req.setRequestHeader('responseType','application/json');
req.setRequestHeader('Access-Control-Allow-Credentials' , 'true');
req.setRequestHeader('Access-Control-Allow-Origin','*');
req.setRequestHeader('Access-Control-Allow-Methods','GET');
req.setRequestHeader('Access-Control-Allow-Headers','application/json');

req.onload = ()=>{

  var res = JSON.parse(req.responseText);
  console.log('the response from the server = > ',res)
}
const data = new FormData();
data.append('x', y);
req.send(data);

蟒蛇

from flask import Flask
from flask_cors import CORS ,cross_origin
app = Flask(__name__)

cors = CORS(app)


@app.route("/test" ,methods = ["POST"] )
def req():
    y = request.form.get("x")
    z = jsonify({"success":y, 'headers': {
    'Access-Control-Allow-Credentials' : 'true',
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods':'GET',
    'Access-Control-Allow-Headers':'application/json',
  }})
    z = request.form.get("x")

    print(f'ive recieved this \n\n {z}') // x is printed fine.

    return jsonify({"success":z})

我可以在控制台中看到 Python 已经接收并打印了 AJAX 对象,但没有将响应发送到 javaScript

标签: javascriptpythonajaxgoogle-chromegoogle-chrome-extension

解决方案


推荐阅读