首页 > 解决方案 > API 获取跨域问题 - 跨域读取阻塞 (CORB)

问题描述

我正在尝试使用 API 根据用户 ID 获取有关特定用户的信息。我需要使用基本身份验证并在我的调用中传递一些标头。我得到这个:

Cross-Origin Read Blocking (CORB) blocked cross-origin response  "rest/user/getProfile?callback=jQuery224033348109431646855_1548684613983&userId=24068..." with MIME type text/plain.

我的代码:

$.ajax
  ({
    type: 'GET',
    crossDomain: true,
    async: false,
    url: 'example_URL_/api/user/getProfile',
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic ZHVubmVzYXBpskjoi43u5409543o9tI654kjhugjy"); },
    dataType: 'jsonp',
    data: { "Id": "1234" },
    success: function (data) {
      console.log(data);
    },
    error: function (xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.log(error);
    }
  });

有什么我想念的吗?

标签: javascriptajaxrestapiget

解决方案


你说:

dataType: 'jsonp',

... 所以 jQuery 发出一个 JSONP 请求(即插入一个<script>元素)。

浏览器向 URL 发出请求,服务器说:

Content-Type: text/plain

由于纯文本文档不是 JavaScript 程序,浏览器拒绝执行它并抛出一个 CORB 错误。

JSONP 响应必须是application/javascript,而不是text/plain

您需要:

  • 不请求 JSONP
  • 更改服务器以使用 JSONP 响应

旁白:由于您使用的是 JSONP,因此typecrossDomainasyncheadersxhr.setRequestHeader属性无效。

由于您说您需要设置基本身份验证,因此排除了选项二。您不能为此使用 JSONP。


推荐阅读