Problem Querying REST API from React + Node

Solved
Highlighted
Shopify Partner
20 2 13

@Ireneludi  ahh, did you install the koa router npm package?

 

npm install --save koa-router

If not, stop your server, run the above command, and start your server again.

0 Likes
Highlighted
Tourist
9 0 1

@Thresher Yes, I installed at very first.

QAQ I have been stuck with this API problem for the whole week....

0 Likes
Highlighted
Tourist
9 0 1

Finally figure it out. The issue was related with chrome security, after I disable chrome cors, everything works fine.

1 Like
Highlighted
Shopify Partner
26 0 7

Hello @Thresher, isn't a risky approach to store the accessToken into a cookie ? 

Wouldn't be better to: 
1) verify request is coming from your domain and avoid extra jobs if not 

2) get the stored access token from your DB using the shop name 

3) make the Shopify request 

4) return data 

 

cheers

 

Robots Hate Monkeys
0 Likes
Highlighted
Shopify Partner
20 2 13

Yes @RHM , that's what I'm doing now!

0 Likes
Highlighted
Excursionist
21 0 3

I don't think disabling cross origin security in the browser is the solution.

1 Like
Highlighted
Tourist
14 0 1

Sorry for digging an old thread but it has part of the solution I need, and it's in the exact same context, query the API from the backend.

const fetchUrl = 'https://getordertest.myshopify.com/api/orders.json';
		const method = "GET";
		fetch(fetchUrl, {method: method,})
		.then(response=>response.json()).then(json => console.log(json))

The code above, is calling the orders api, which is what I need. But I have no idea where to insert this snippet.
Should I wrap it in a server.use? or maybe in a router.get? How do I make it trigger?
Even if its just for a test as soon as the server launches would do for me to get moving. I'm stuck trying to understand how to call the APIs for a long time.

0 Likes
Highlighted
Tourist
9 0 1

I used in router.get(`insert the code snippet here`)
Basically what I do is, from client, call my backend, and in backend router, call Shopify API

0 Likes
Highlighted
Excursionist
21 0 3

Your best bet is to use the shopify-api-node package so that proper headers are sent for auth without having to manually configure them. All of this should happen on your server and not on the client so as not to expose your accessToken.

0 Likes
Highlighted
Excursionist
17 1 3

@Thresher thanks for this post.

 

I implemented it almost exactly as you all have outlined but when I call `/api/products` or anything else I get a 404 error.  Any idea what's up?  Here is the relevant server code.  TBH I dont see where the server is using the routes based on this code.

 

app.prepare().then(() => {
  const server = new Koa();
  server.use(session(server));
  server.keys = [SHOPIFY_API_SECRET_KEY];

  server.use(
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY,
      secret: SHOPIFY_API_SECRET_KEY,
      scopes: ['read_products'],
      afterAuth(ctx) {
        const { shop, accessToken } = ctx.session;

        console.log('cookie', shop)
        ctx.cookies.set('shopOrigin', shop, { httpOnly: false });
        ctx.cookies.set('accessToken', accessToken, { httpOnly: false });

        ctx.redirect('/');
      },
    }),
  );

  server.use(verifyRequest());
  server.use(async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
    return
  });

  router.get('/api/:object', async (ctx) => {
    try {
      const results = await fetch("https://" + ctx.cookies.get('shopOrigin') + "/admin/api/2019-10/" + ctx.params.object + ".json", {
        headers: {
          "X-Shopify-Access-Token": ctx.cookies.get('accessToken'),
        },
      })
        .then(response => response.json())
        .then(json => {
          console.log('json', json)
          return json;
        });
      ctx.body = {
        status: 'success',
        data: results
      };
    } catch (err) {
      console.log(err)
    }
  })

  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});
0 Likes