首页 > 解决方案 > 404 在 server.js (Koa.js) 上找不到路由处理程序的获取请求

问题描述

我在 Chrome 控制台中看到此错误(https://8e2dac99.ngrok.io/是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====="

这个 React.js 函数调用它(方法 local 设置为“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=====`);
    }
  }

这是 server.js 中的路由处理程序,嵌套在 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=====`);
    }

有谁知道为什么找不到上述路线?我重新启动了 koa 服务器,但没有帮助。

标签: javascriptrouteskoa.js

解决方案


将通配符添加到您的路由处理程序。koa-router与您的模式与两个斜杠不匹配。

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

推荐阅读