Search code examples
reactjsrestkoashopify-appscript-tag

Shopify App - Script Tag - CORS error when retrieving data from store


Overview

I have a custom REST API within my Koa server and I can access it just fine within my Shopify app using react. However, when I try to access it from my Script Tag, I get a CORS error.

Issue

I can't access my custom REST API data from the script tag, but I can access it from Postman & my React app.

What I tried

  1. Install koa/cors and set {origin: *}

Code

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);
  }

Any ideas how I can go around this without using cors-anywhere? Thank you very much in advance.

Images API request


Solution

  • It ended up being a silly mistake. I had to add the koa-cors middleware before all the others. Therefore, in the server.js file it should be like this:

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