【发布时间】:2021-08-25 04:46:38
【问题描述】:
我正在尝试在我的反应网站上进行 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 登录。
感谢您的帮助!
【问题讨论】:
-
您需要用户实际访问重定向页面,而不是发出获取请求。使用链接,而不是按钮。
-
fetch()调用不会导致浏览器重定向。您只需使用Location标头中的重定向 URL 将 302 响应从提取返回到您的 Javascript。如果您希望浏览器重定向,则由运行fetch()调用来更改window.location的 Javascript 决定。 -
我无法直接访问重定向页面我需要通过重定向。使用 Link 组件访问 /oauth 页面不起作用并返回 404