简体   繁体   English

Express res.redirect 重定向未按预期工作

[英]Express res.redirect redirect not working as expected

I have an express app.我有一个快速应用程序。 I am adding a middleware which redirects user to logout if token is invalid .我正在添加一个中间件,如果令牌无效,它会将用户重定向到注销。

export async function validateAuthTokenMiddleware(
    req: Request,
    res: Response,
    next: NextFunction,
): Promise<NextFunction | void> {
    try {
        const { context } = req;
        await validateToken(context);
        next();
    } catch (err) {
        logoutAndRedirectUser(res);
    }
}

Code for logoutAndRedirectUser logoutAndRedirectUser的代码

const logoutUser = (res: Response) => {
    res.clearCookie('my_token')
    res.format({
        json: () =>
            res.status(401).json({
                errors: [
                    {
                        message: 'You must login to see this',
                        errorCode: '0001',
                    },
                ],
                extensions: {
                    location: location,
                },
            }),
        html: () => res.redirect(302, location),
        default: () => res.redirect(302, location),
    });
};

I am using this middleware in my route like so.我像这样在我的路线中使用这个中间件。 All api request from client goes via this route:来自客户端的所有 api 请求都通过以下路线:

router.use('/api', validateAuthTokenMiddleware, graphql);

However the redirect is not working as expected.但是重定向没有按预期工作。

  • I am expecting my browser to get redirect to my '/login' route/page after clearing cookie.我希望我的浏览器在清除 cookie 后重定向到我的“/登录”路由/页面。 Instead I see just 401 for my /api call and browser remains on same page.相反,我的/api调用只看到 401,并且浏览器仍然在同一页面上。 res.redirect(302, '/login') is not triggered. res.redirect(302, '/login') 没有被触发。
  • I have tried refactoring logoutUser to just send res.redirect(302, '/login') Instead of res.json.我尝试重构logoutUser只发送res.redirect(302, '/login')而不是 res.json。 Still doesn't work.还是不行。

Network snapshot as observed on browser:在浏览器上观察到的网络快照: 在此处输入图像描述

My browser makes simple requests with我的浏览器发出简单的请求

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,...

This means that application/json is acceptable (because of */*;q=0.8 ), therefore your json response is chosen, which is not a redirect.这意味着application/json是可接受的(因为*/*;q=0.8 ),因此选择了您的 json 响应,这不是重定向。 Perhaps reordering the choices within res.format helps.也许重新排序res.format中的选择会有所帮助。

You wrote:你写了:

I have tried refactoring logoutUser to just send res.redirect(302, '/login') Instead of res.json.我尝试重构 logoutUser 只发送 res.redirect(302, '/login') 而不是 res.json。 Still doesn't work.还是不行。

Can you share your refactored code as well, please?您也可以分享您的重构代码吗?

I end up setting a condition on my Client code.我最终为我的客户代码设置了一个条件。 If received 401, redirect to login page.如果收到 401,则重定向到登录页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM