首页 > 解决方案 > 获取端点后的快速重定向不起作用

问题描述

我正在尝试在我的反应网站上进行 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 登录。

谢谢你的帮助!

标签: reactjsexpress

解决方案


对于任何想知道为什么res.redirect(url)返回 404 的人,很可能您还没有设置反向代理,并且所有路由都只重定向到前端。要解决这个问题,请确保您的所有后端端点都有一个共同的基础,例如 /api/xxx 并为所有以 /api 开头的 url 设置一个反向代理


推荐阅读