【问题标题】:Express redirection after fetching endpoint doesn't work获取端点后的快速重定向不起作用
【发布时间】: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

标签: reactjs express


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2018-09-03
    • 1970-01-01
    • 2013-11-07
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多