Displaying Data From Server to Frontend

Saadkun
New Member
5 0 0

Hello everyone, I found this problem while Creating a REST API inside my server.js 

import "@babel/polyfill";
import dotenv from "dotenv";
import "isomorphic-fetch";
import createShopifyAuth, { verifyRequest } from "@shopify/koa-shopify-auth";
import graphQLProxy, { ApiVersion } from "@shopify/koa-shopify-graphql-proxy";
import Koa from "koa";
import next from "next";
import Router from "koa-router";
import session from "koa-session";

dotenv.config();
const port = parseInt(process.env.PORT, 10) || 8081;
const dev = process.env.NODE_ENV !== "production";
const app = next({
  dev,
});
const handle = app.getRequestHandler();
const { SHOPIFY_API_SECRET, SHOPIFY_API_KEY, SCOPES} = process.env;


app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();
  server.use(
    session(
      {
        sameSite: "none",
        secure: true,
      },
      server
    )
  );
  server.keys = [SHOPIFY_API_SECRET];
  server.use(
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY,
      secret: SHOPIFY_API_SECRET,
      scopes: [SCOPES],

      async afterAuth(ctx) {
        // Access token and shop available in ctx.state.shopify
        const { shop } = ctx.state.shopify;

        // Redirect to app with shop parameter upon auth
        ctx.redirect(`/?shop=${shop}`);
      },
    })
  );
  server.use(
    graphQLProxy({
      version: ApiVersion.October19,
    })
  );

  router.get("(.*)", verifyRequest(), async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  });
  

router.get('/api/products',verifyRequest(), async(ctx) => {
  try {
    ctx.body = {
      status:'succes',
      data:'this is the public api'
    }
  } catch (error) {
    console.log(error);
  }
})
  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

I want to fetch the public API '/api/product/' but all I get is the following error : 

Saadkun_0-1615135354287.png

how can I create a public API inside my app.prepare

 

0 Likes
johna1203
Tourist
4 1 0

I have recently started with shopify and am still studying it. but calling the api with verifyRequest() I am using authenticatedFetch(). it adds the access_token to the header and with that can pass verifyRequest() with no problem.

import {Heading, Page} from "@shopify/polaris";
import {useAppBridge} from "@shopify/app-bridge-react";
import {authenticatedFetch} from "@shopify/app-bridge-utils";


const Index = () => {
  const app = useAppBridge();
  authenticatedFetch(app)("/api/products").then(res => res.json()).then(res => {
    console.log(res.name);
  });

  return (
    <Page>
      <Heading>Test</Heading>
    </Page>
  );
}

export default Index;

 

 

0 Likes