express - 跨域Auth0认证
问题描述
我的后端使用 Auth0 验证了以下端点
api.mysite.com/auth/login
api.mysite.com/auth/logout
api.mysite.com/ → returns “logged in” or “logged out”
我的后端是一个快递服务器
另一方面,如果我在 mysite.com 上的前端打开控制台,fetch(‘api.mysite.com’)
即使在新选项卡中导航到 api.mysite.com 给我“logged in”,也会返回“logged out”。
我将 https://*.mysite.com 列入“允许的 Web 来源”和“允许的来源”下的白名单,但我无法弄清楚为什么我无法访问我的 API。
提前致谢
应该注意的是,我在 api.mysite.com/auth/login 使用通用登录
解决方案
这是我的 cors middelware
import { NextFunction, Request, Response } from "express";
const corsMiddleware = (req: Request, res: Response, next: NextFunction) => {
const allowedDomains = [
"http://localhost:4200",
"https://sample.ir",
"https://sample.ir"
];
if (allowedDomains.indexOf(req.headers.origin) !== -1) {
const index: number = allowedDomains.indexOf(req.headers.origin);
res.header("Access-Control-Allow-Origin", allowedDomains[index]);
}
res.header("Access-Control-Allow-Headers", "Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Max-Age", "3600");
// if (req.url.search("public") == -1) {
// res.header("content-type", "application/json; charset=utf-8");
// }
const method = req.method;
if (method == "OPTIONS") {
// res.header("HTTP/1.1 200 OK CORS");
return res.status(200).json({});
}
next();
};
export default corsMiddleware;
推荐阅读
- java - 如何链接 java 脚本并在 python 脚本中运行它们?
- reactjs - 如何使用 react-google-maps 将 GoogleMap React 组件重新居中到新地址?
- linux - Jenkins 在没有权限的情况下如何在 ubuntu 中与 jenkins 用户一起构建?
- linux - 在输出的开头和结尾添加花括号
- apache - 从 PyCharm 访问 API 时出现 Http 错误 502
- mongodb - Pod 重启后 Kubenetes Mongo 部署丢失数据
- dns - 使用 hmailserver 的 SMTP 服务器。主机无法解析为类型
- swift - 如何在 CP 模板中进行 uiview
- ms-access - 错误:查询输入必须包含至少一个表或查询
- scala - 如何在 IntelliJ 中添加新的 SBT 模块?