【问题标题】:How to fetch the data from the url if the response coming is opaque. mode: "no-cors" is not showing any effect如果响应不透明,如何从 url 获取数据。模式:“no-cors”没有显示任何效果
【发布时间】:2021-08-25 12:28:23
【问题描述】:

在获取链接响应时,应该给我一个包含两个值的数组,但这里的响应显示如下。
控制台中的响应: 响应 {type: "opaque", url: "", redirected: false, status: 0, ok: false, ...}

  index.js:1 Error: Error: Could not fetch user roles data!
  at fetchData (role-actions.js:12)
  at async role-actions.js:21

**code:**
export const fetchRoleData = () => {
  return async (dispatch) => {
    const fetchData = async () => {
    const response = await fetch("https://api.saaspect.com/user/roles", {
    mode: "no-cors",
    });
    console.log("response", response);
    if (!response.ok) {
      throw new Error("Could not fetch user roles data!");
    }

    const data = await response.json();

    return data;
    };

    try {
      const roles = await fetchData();
      console.log("inside try");
      dispatch(
        uiActions.showUserRoles({
          userRoles: roles.items || [],
        })
      );
   } catch (error) {
     console.error("Error:", error);
   }
 };
 };

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你不能。不透明意味着响应是一个你看不到里面的盒子。

    mode: 'no-cors' 仅在您需要发送请求并且没有看到响应时才有用。

    如果你想查看它的内部,你需要mode: 'cors' 和服务器的权限(根据 CORS 规范)才能读取响应。

    【讨论】:

    • 如果我尝试使用 mode:"cors" 或使用它提供的任何方法访问它,例如 Access to fetch at 'api.saaspect.com/user/roles' from origin 'localhost:3000' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
    • @Soumya — 是吗?正如我所说,一个不透明的响应满足您的需求,并且您需要根据 CORS 规范获得 api.saaspect.com 的许可。
    • 好吧,那我好像拿不到了
    猜你喜欢
    • 2019-03-05
    • 2012-11-09
    • 2018-05-07
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多