Koa.js:ctx.setcookie()无法设置cookie

问题描述 投票:0回答:1

在下面的server.js代码中,我正在设置一个中间件,该中间件应通过Shopify OAuth,然后重定向到/路由。

'/'路由及其重定向网址已加载到shopify管理员区域内的iframe中。我确实看到了/重定向到的页面。但是没有cookie。

与cookie设置有关,我正在Web浏览器和安全的https连接上访问此路由。

我正在使用Google Chrome版本79.0.3945.88(官方内部版本)(64位)。我还使用EditThisCookie浏览器扩展程序来查看域中存在的cookie。

谁能告诉我为什么我要在server.js中设置的cookie无法设置?

import "isomorphic-fetch";
require("dotenv").config();

import Koa from "koa";
import Router from "koa-router";
import session from "koa-session";
import authorizeForShopify, {verifyRequest} from "@shopify/koa-shopify-auth";

const koa = new Koa();
const router = new Router();

const {SHOPIFY_BUYUSED_API_KEY, SHOPIFY_BUYUSED_API_SECRET, SHOPIFY_BUYUSED_SCOPES} = process.env;

koa.keys = [SHOPIFY_BUYUSED_API_SECRET];
koa.use(session({secure: true, sameSite: "none"}, koa));


////// Shopify OAuth //////
koa.use(authorizeForShopify({
  apiKey : SHOPIFY_BUYUSED_API_KEY
  , secret : SHOPIFY_BUYUSED_API_SECRET
  , scopes : SHOPIFY_BUYUSED_SCOPES.split(",")
  , afterAuth(ctx: Koa.Context): void {
    console.log(`=====inside afterAuth()=====`); // I don't see this log statement
    const {shop, accessToken} = ctx.session;

    console.log({ // also I do not see this one
      message : "from inside afterAuth()"
      , shop
      , accessToken
    });

    // cookie setting
    const cookieOptions = { 
      httpOnly: true,
      secure: true,
      signed: true,
      overwrite: true
    };

    // neither cookie is present in EditThisCookie
    ctx.cookie.set("buyUsed_shopName", shop, cookieOptions);
    ctx.cookie.set("buyUsed_generalToken", accessToken, cookieOptions);


    ctx.redirect("/");
  }
}));


////// Routing //////

router.get('/', async ctx => {
  // ctx.body = "Koa server running, '/' route triggered"
  ctx.redirect("https://storage.cloud.google.com/buy_used/consoleLog.js");
});


koa.use(verifyRequest());

koa.use(router.routes())
  .use(router.allowedMethods());

const port: number = Number(process.env.PORT) || 8080;

koa.listen(port, undefined, undefined, () => console.log(`=====Koa listening on port ${port.toString()}=====`));


node.js cookies koa
1个回答
0
投票

[对于Koa,使用cookie的方法是ctx.cookies.getctx.cookies.set。因此,这些行应更改为:

// neither cookie is present in EditThisCookie
ctx.cookies.set("buyUsed_shopName", shop, cookieOptions);
ctx.cookies.set("buyUsed_generalToken", accessToken, cookieOptions);
© www.soinside.com 2019 - 2024. All rights reserved.