【问题标题】:Shopify App - Script Tag - CORS error when retrieving data from storeShopify 应用程序 - 脚本标签 - 从商店检索数据时出现 CORS 错误
【发布时间】:2020-09-26 20:50:18
【问题描述】:

概述

我的 Koa 服务器中有一个自定义 REST API,我可以在我的 Shopify 应用程序中使用 react 很好地访问它。但是,当我尝试从我的脚本标签访问它时,我收到了 CORS 错误。

问题

我无法从脚本标签访问我的自定义 REST API 数据,但我可以从 Postman 和我的 React 应用程序访问它。

我尝试了什么

  1. 安装koa/cors并设置{origin: *}

代码

server.js

   server
      .use(router.routes())
      .use(router.allowedMethods())
      .use(CORS({ origin: "*" }));

      router.get("/api/test", async (ctx, next) => {
        ctx.body = {
          llama: "123",
        };
      });

script_tag.js

  async function hello() {
    await _loadScript(
      "https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js",
    );
    const data = await window.axios.get(
      "https://3b1b4258759f.ngrok.io/api/test?shop=panda-app-tests.myshopify.com",
      {
        crossDomain: true,
      },
    );
    console.log(data);
  }

有什么想法可以在不使用cors-anywhere 的情况下解决这个问题吗?非常感谢您。

图片

【问题讨论】:

    标签: reactjs rest koa shopify-app script-tag


    【解决方案1】:

    这最终变成了一个愚蠢的错误。我必须在所有其他中间件之前添加 koa-cors 中间件。因此,server.js 文件中应该是这样的:

    server
      .use(CORS({ origin: "*" }))
      .use(router.routes())
      .use(router.allowedMethods());
    

    【讨论】:

    • 非常感谢!解决了我因 Option-Preflight 请求而阻止请求的问题。
    • 不客气,我的朋友!祝您有个愉快的一周。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2020-07-21
    • 2017-09-15
    相关资源
    最近更新 更多