reactjs - 获取端点后的快速重定向不起作用
问题描述
我正在尝试在我的反应网站上进行 tiktok 身份验证。按照 tiktok api 文档,我创建了一个带有 oauth 端点的 epxress 服务器:
app.get("/oauth", (req, res) => {
const csrfState = Math.random().toString(36).substring(7);
res.cookie("csrfState", csrfState, { maxAge: 60000 });
let url = "https://open-api.tiktok.com/platform/oauth/connect/";
url += `?client_key=${CLIENT_KEY}`;
url += "&scope=user.info.basic,video.list";
url += "&response_type=code";
url += `&redirect_uri=${REDIRECT_URI}`;
url += `&state=${csrfState}`;
res.redirect(url);
});
这应该将用户重定向到 tiktok 登录页面:/ 这是我的反应前端中的按钮组件:
const TiktokLogin = ({ cssClass }) => {
const handleClick = (e) => {
e.preventDefault()
// eslint-disable-next-line no-console
console.log("Log in");
fetch("/oauth").then(r => console.log(r))
};
return (
<button type="button" className={cssClass} onClick={handleClick}>
Identify me with <i className="fab fa-tiktok" />
</button>
);
};
但是,当我单击该按钮时,不仅我没有被重定向,而且我收到了几个错误:
Access to fetch at 'https://open-api.tiktok.com/platform/oauth/connect/?client_key=xxxx&scope=user.info.basic,video.list&response_type=code&redirect_uri=https://localhost:3000/signup&state=xxxx' (redirected from 'https://localhost:3000/oauth') from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET https://open-api.tiktok.com/platform/oauth/connect/?client_key=xxxx&scope=user.info.basic,video.list&response_type=code&redirect_uri=https://localhost:3000/signup&state=xxxx net::ERR_FAILED
简而言之:我需要我的按钮将用户发送到 /oauth 端点,然后该端点应该将用户重定向到 tiktok 登录。
谢谢你的帮助!
解决方案
对于任何想知道为什么res.redirect(url)
返回 404 的人,很可能您还没有设置反向代理,并且所有路由都只重定向到前端。要解决这个问题,请确保您的所有后端端点都有一个共同的基础,例如 /api/xxx 并为所有以 /api 开头的 url 设置一个反向代理
推荐阅读
- javascript - Discord Bot 随机回复执行命令
- c - 编译时检查枚举成员是否存在
- javascript - 通过 _id 查找 MongoDB 文档在 ObjectId 的类型上失败
- javascript - 为平面列表中的每个项目添加两个按钮
- python - 未使用的导入使我可以访问信号的标准输出
- java - 嵌套异常是 org.hibernate.HibernateException:当未设置“hibernate.dialect”时,对 DialectResolutionInfo 的访问不能为空
- c# - 无法隐式转换类型'System.Collections.Generic.List<
完整的异常消息:
无法将类型 'System.Collections.Generic.List<<anonymous type: Schedular.API.Models.TaskSchedule schedule, Schedular.API.Models.Note note&
- python - 创建一个函数来计算一个没有内置方法的数字的对数
- flutter-layout - ScrollExtent 在颤动中为负
- azure - 免费试用订阅已禁用,因为没有剩余额度