【问题标题】:Cross-Origin Read Blocking Error in reactjsreactjs中的跨域读取阻塞错误
【发布时间】:2019-07-13 00:12:05
【问题描述】:

我正在学习 ReactJS。我正在使用 fetch 从 API 获取数据。我使用了下面的代码。

 fetch('http://myurl.com/api')
              .then(res => res.json())
              .then(res => console.log(res));

API 的状态为 200 ok,但响应 Nothing to Preview 并在控制台中低于错误

跨域读取阻塞 (CORB) 阻止了跨域响应 http://myurl.com/api 带有 MIME 类型 应用程序/json。看 https://www.chromestatus.com/feature/5629709824032768 了解更多 详情。

我还在下面的代码中添加了标题。

 fetch("http://xxx.xxx.xxx.xxx:8081/api/category/popular",{
                 method: 'GET',
                  headers: {
                    'Access-Control-Allow-Origin': '*',
                  },
              })

我在 API 响应中有以下 json

  {  
   "data":[  
      {  
         "parent_id":"5c2f74e0a4d846591b2b1a40",
         "icon":"http://myurl.in:8081/default.png",
         "_id":"5c2f74e8a4d846591b2b1a41",
         "name":"Shop",
         "modified_at":"2019-01-04T14:59:52.791Z",
         "created_at":"2019-01-04T14:59:52.791Z"
      },
      {  
         "parent_id":"5c2f74e0a4d846591b2b1a40",
         "icon":"http://myurl.in:8081/default.png",
         "_id":"5c2f7566a4d846591b2b1a42",
         "name":"Home Service",
         "modified_at":"2019-01-04T15:01:58.507Z",
         "created_at":"2019-01-04T15:01:58.507Z"
      },
      {  
         "parent_id":"5c2f74e0a4d846591b2b1a40",
         "icon":"http://myurl.in:8081/default.png",
         "_id":"5c5c2dd30d017c401ec17253",
         "name":"Test",
         "modified_at":"2019-02-07T13:08:35.653Z",
         "created_at":"2019-02-07T13:08:35.653Z",
         "__v":0
      }
   ]
}

【问题讨论】:

  • "Nothing to Preview" — 所以响应是空白的,这意味着它不是有效的 JSON,因此它会退回安全功能。即使没有,它也会抛出解析错误,因为它不是有效的 JSON。您需要修复 API,使其返回一些实际的 JSON。我们无法告诉您如何执行此操作,因为您的服务器端代码丢失。
  • 看到了,我觉得对你有帮助>>stackoverflow.com/questions/52728346/…
  • @Quentin 如果这个 api 在邮递员中命中,日期显示
  • @SagarKodte — 是否用 JSON 表示? GET 请求是带有“Nothing to Preview”的请求还是存在 OPTIONS 请求?是否有任何其他错误消息?

标签: javascript reactjs cross-origin-read-blocking


【解决方案1】:

通常需要在 API 服务器中设置允许的请求域的 CORS 标头(需要更改服务器)。

【讨论】:

    【解决方案2】:

    跨域读取阻塞 (CORB)。它旨在防止浏览器向网页传递某些跨域网络响应。

    首先确保这些资源使用正确的“Content-Type”,即 JSON MIME 类型 - “text/json”、“application/json”、HTML MIME 类型 - “text/html”。

    第二:将凭证设置为同源

     fetch("https://example.com/api/request", {
                method: 'GET',
                body: JSON.stringify(data),
                credentials: "same-origin", //include, same-origin
                headers: {Accept: 'application/json', 'Content-Type': 'application/json',},
            })
        .then((data) => data.json())
        .then((resp) => console.log(resp))
        .catch((err) => console.log(err))
    

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 2019-04-14
      • 2021-08-07
      • 2020-04-25
      • 2018-11-25
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多