我正在构建一个前端使用 Angular 的网页(通过 GitHub Pages 提供服务),后端使用 Google Cloud Functions / Node.js。
例如,有一条路线
/api/user/create
,其中使用 Angular HttpClient 发出 POST 请求,设置 { withCredentials: true }
。如果我直接访问https://striderhobbit.github.io/psycho-cli
,一切正常。
但是,如果我在 GitHub Pages 上设置了自定义域 (
https://www.tecstures.com
),则事实并非如此。我可以登录,接收响应 cookie
connect.sid
expires "2024-04-09T09:06:23.000Z"
path "/"
samesite "None"
secure true
value "s:p6moM7Q_zD50xUsCl2ns8kA608tE1qb4.zkz7Y91fcqs+YTfVdtKV4yAqnTofhPogvhdWMo0g2yQ"
但是
/api/user/create
大多数时候失败,因为没有发送回cookie/会话丢失(我在开发工具中检查:请求cookie为空)。在极少数情况下,它可以正常工作,无需更改任何代码。 所以我只能怀疑它必须对服务器响应时间做一些事情。
但请注意:它一定与在 GitHub 中设置自定义域有关,因为没有它就一直有效。
服务器看起来像(express + express-session):
const app = express();
app.use(
cors({
origin: ["https://tecstures.com", "https://striderhobbit.github.io"],
credentials: true,
})
);
app.set("trust proxy", true);
app.use(express.json());
app.use(
session({
cookie: {
maxAge: 300000,
httpOnly: false,
secure: true,
sameSite: "none",
partitioned: true,
},
resave: false,
saveUninitialized: false,
secret: generate(10),
})
);
在 GitHub 上一切看起来都很好:
在 squarespace (托管我的自定义域的地方)我有
更新
要重现,请访问 https://tecstures.com/#/events,然后按照以下步骤操作:
你应该得到一个错误
Error: Missing authentication at EventService.authorize (/workspace/lib/src/services/base.js:13:19)...
我可以通过实施 openapi-generator-cli 来解决这个问题。另外,在 iOS 中,您必须在 Safari 设置中启用
Disable Cross-Origin Restrictions
。
这是有效的设置:
app.use(
cors({
origin: [
...
],
credentials: true,
})
);
app.set("trust proxy", true);
app.use(
session({
cookie: {
httpOnly: true,
secure: true,
sameSite: "none",
partitioned: true,
},
...
})
);