How I can sent a request from React to Koa server api?

Anonymous
Not applicable
1808 0 0

Hi 

I want to use some custom apis within Koa and I need to send a request from React to the api

server.post('/images', ..)

But getting 404 error and I don't know what I am doing wrong. 

 

React sends a request to 

https://028fbf52d955.ngrok.io/images

 

Here is an example:

server.js

require('isomorphic-fetch');
const Koa = require('koa');
const next = require('next');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const dotenv = require('dotenv');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const session = require('koa-session');
const Router = require('koa-router');
const cors = require('@koa/cors');

dotenv.config();
const { default: graphQLProxy } = require('@shopify/koa-shopify-graphql-proxy');
const { ApiVersion } = require('@shopify/koa-shopify-graphql-proxy');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const { SHOPIFY_API_SECRET_KEY, SHOPIFY_API_KEY } = process.env;

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();
  server.use(cors());
  server.use(session({ sameSite: 'none', secure: true }, server));
  server.keys = [SHOPIFY_API_SECRET_KEY];

  server.use(
    createShopifyAuth({
      apiKey: SHOPIFY_API_KEY,
      secret: SHOPIFY_API_SECRET_KEY,
      scopes: ['read_products', 'write_products'],
      afterAuth(ctx) {
        const { accessToken } = ctx.session;
        const urlParams = new URLSearchParams(ctx.request.url);
        const shop = urlParams.get('shop');


        ctx.redirect(`/?shop=${shop}`);
      },
    }),
  );
  server.use(graphQLProxy({ version: ApiVersion.April20 }))
  server.use(verifyRequest());
  server.use(async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;

  });

  router
    .post('/images', verifyRequest, (ctx, next) => {
      // handle your post request here
      console.log(ctx.request.body)
      ctx.body = ctx.request.body;
    });

  server
    .use(router.routes(),
      router.allowedMethods())


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

 React Component

import { Card, Layout, Page, Button, ButtonGroup, Stack, Heading, ProgressBar } from '@shopify/polaris';
import React, { Component } from 'react';

class Progress extends Component {
  state = {}

  render() {
    fetch('/images', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ a: 1, b: 'Textual content' })
    });

    return (
      <Page>
        <Layout.AnnotatedSection
          title="Queue"
          description="Check the status of your work..">
          <Card sectioned>
            <ProgressBar progress={40} size="small" />
            <Card.Section>
              <Stack>
                <Stack.Item fill>
                  <Heading>Order #1136</Heading>
                </Stack.Item>
                <Stack.Item>
                  <ButtonGroup>
                    <div style={{ color: '#bf0711' }}>
                      <Button monochrome outline>
                        Stop
                    </Button>
                    </div>
                    <Button primary>Revert</Button>

                  </ButtonGroup>
                </Stack.Item>
              </Stack>
            </Card.Section>
          </Card>
        </Layout.AnnotatedSection>
      </Page >
    );
  }
}

export default Progress;

 

0 Likes