使用模式时的身份验证错误:在 React 中使用 fetch 的 no-cors

Authentication Error when using mode: no-cors using fetch in React

我正在构建一个 React 应用程序,它为我们的内部开发人员从服务中提取不同的统计数据(提交、跟踪时间等)。

我正在使用 fetch 从时间跟踪应用程序 Harvest 中获取 API 数据。根据 their docs,您可以使用基本的 HTTP 身份验证。当我使用应用程序 Postman 时,一切都很好,我可以看到很好的响应。最初我使用:

getHarvest(){
    // Set Harvest Headers
   const harvestHeaders = {
     method: 'GET',
     headers: {
       'Authorization': 'Basic xxxxxxxxxxxxxxx=',
       'Content-Type': 'application/json',
       'Accept': 'application/json',
       'Cache-Control': 'no-cache',
     }
   };

   fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
   .then( response => response.json() )
   .then( projects => {

    // Do some stuff


   } )
  }

这让我在控制台中出错:

Fetch API cannot load https://myaccount.harvestapp.com/projects/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

根据反馈,我将函数更改为如下所示:

getHarvest(){
    // Set Harvest Headers
   const harvestHeaders = {
     method: 'GET',
     mode: 'no-cors',
     headers: {
       'Authorization': 'Basic xxxxxxxxxxxxxxx=',
       'Content-Type': 'application/json',
       'Accept': 'application/json',
       'Cache-Control': 'no-cache',
     }
   };

   fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
   .then( response => response.json() )
   .then( projects => {

    // do stuff


   } )
  }

但这会导致身份验证错误:

GET https://myaccount.harvestapp.com/projects/ 401 (Unauthorized)

我不确定如何才能正确获得响应。难道我做错了什么?对我来说,使用 Postman 应用程序似乎很奇怪,但事实并非如此。想法?谢谢!

Harvest API 似乎并不适合与 XHR 或从 Web 应用程序获取。

至少 their docs 没有提及任何有关使用 XHR 或 Fetch 中的 API 的内容,这些文档也没有提及任何有关 Access-Control-Allow-Origin 或 CORS 的内容。

相反,文档给出了将 API 与 curl 和 Postman REST 客户端一起使用的示例。

并在下面的文档中尝试示例,响应没有 Access-Control-Allow-Origin

curl -H 'Content-Type: application/xml' -H 'Accept: application/xml' \
  -u "user@example.com:password" https://example.harvestapp.com/account/who_am_i

所以答案似乎是:您无法通过 Web 应用程序使用 XHR/Fetch 访问 Harvest API。

它在 Postman 中有效,因为 Postman 不受 same-origin 策略的约束浏览器强制执行以防止浏览器中的 Web 应用 运行 发出 cross-origin 请求,除非 site/endpoint 请求已选择使用 CORS(Harvest 似乎尚未选择)。