首页 > 解决方案 > 当 url 输入浏览器返回预期数据时,fetch() 返回不透明

问题描述

我有一个反应应用程序,它可以获取我编写的 WebAPI。这是 WebAPI 的 URL:

http://ec2-54-70-8-113.us-west-2.compute.amazonaws.com/api/homepage

当我在浏览器中输入 webAPI 的 url 时,我得到了这个:

<ArrayOfHomepage xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebAPI">
    <Homepage>
        <product_description>
            This application will allow the user to use his/her device camera to scan a product barcode and look up the value of the prodcut on Amazon and eBay based on the products barcode
        </product_description>
        <product_title>What's my crap worth</product_title>
        <return_code>1 - successful read from database</return_code>
    </Homepage>
</ArrayOfHomepage>

这正是我期望收到的。这是我的 React Fetch() 的代码:

let url = "http://ec2-54-70-8-113.us-west-2.compute.amazonaws.com/api/homepage";

fetch(url, {mode: "no-cors"})
  .then(response => response)
  .then(data => console.log("data: ", data)); 

这就是返回的内容:

Data:
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}

不是我所期待的。当我从 fetch 中删除 {mode: "no-cors"} 参数时,我收到此错误:

No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed access. 
If an opaque response serves your needs, set the request's mode to 'no-cors'
to fetch the resource with CORS disabled.

关于如何通过 fetch 正确检索数据的任何建议?

感谢您的任何建议或意见。

标签: javascriptcorsfetch

解决方案


推荐阅读