Sean D
Sean D

Reputation: 4292

404 not found with fetch request to route handler on server.js (Koa.js)

I'm seeing this error in Chrome console (https://8e2dac99.ngrok.io/ is a local proxy tunnel on http://localhost:3000);

VM76:1 GET https://8e2dac99.ngrok.io/api/2019-10/custom_collections.json 404 (Not Found)
(anonymous) @ VM76:1
_callee2$ @ _app.js:47
tryCatch @ runtime.js:45
invoke @ runtime.js:271
prototype.<computed> @ runtime.js:97
asyncGeneratorStep @ asyncToGenerator.js:5
_next @ asyncToGenerator.js:27
(anonymous) @ asyncToGenerator.js:34
F @ _export.js:36
(anonymous) @ asyncToGenerator.js:23
(anonymous) @ _app.js:48
onClick @ _app.js:79
callCallback @ react-dom.development.js:336
invokeGuardedCallbackDev @ react-dom.development.js:385
invokeGuardedCallback @ react-dom.development.js:440
// continues...

_app.js:57 SyntaxError: Unexpected token < in JSON at position 0 "=====e====="

This React.js function calls it (with the method local set to "get")

  getCollections = async method => {
    const fetchUrl = "/api/2019-10/custom_collections.json";

    try {
      const response = await fetch(fetchUrl, { method });
      const responseBody = await response.json();
      console.log(responseBody, `=====responseBody=====`);
      return responseBody;
    }
    catch (e) {
      console.log(e, `=====e=====`);
    }
  }

This is the route handler in server.js, nested inside app.prepare():

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

      async afterAuth(ctx) {
        const { shop, accessToken } = ctx.session;

        ctx.set({
          "X-Shopify-Access-Token" : accessToken
        });

        ctx.cookies.set("shopOrigin", shop, {
          httpOnly: false
        });
        ctx.redirect("/");
      }
    })
  );
  server.use(
    graphQLProxy({
      version: ApiVersion.October19
    })
  );
  router.get("*", verifyRequest(),
    async ctx => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  });
  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });


  router.get('/api/:requestedResource', async ctx => {
    const shopOrigin = ctx.cookies.get('shopOrigin');
    const accessToken = ctx.cookies.get('accessToken');
    const requestedResource = ctx.params.requestedResource;

    try {
      const response = await fetch(`https://${shopOrigin}/api/2019-10/${requestedResource}.json`, {
        headers : {
        "X-Shopify-Access-Token" : accessToken
        }
      });
      const responseBody = response.json();

      ctx.body = {
        status : 'success'
        , data : responseBody
      }

    } catch (e) {
      console.log(e, `=====error=====`);
    }

Does anyone know why the route is not found with the above? I restarted the koa server but it didn't help.

Upvotes: 1

Views: 547

Answers (1)

Puwka
Puwka

Reputation: 650

add a wildcard to your route handler. koa-router does not match your pattern with two slashes.

router.get('/api/:requestedResource*', async ctx ...)

Upvotes: 0

Related Questions