繁体   English   中英

从fetch api中反应以表达res.redirect

[英]from fetch api in react to express res.redirect

我搜索了很长时间,但找不到答案。

当有人从api,fetch或ajax请求数据时(在SPA中反应)

我只想将数据发送给已登录或已验证的用户,

如果不是登录用户或未认证用户,

我想重定向到“ someReAuthPage”

我的策略如下。

在SPA反应客户端

fetch('/api/someData', {
    method : "GET",
})
.then(......)

在快递服务器中

app.get('/api/:blah', (req, res, next) => {
    if(logged in or authenticated user){
        next()
    } else {
        res.redirect('someReAuthPage')
    }
})


app.get('/api/someData', (req, res) => {
    ..........
    res.json('someJsonData')
}

但是此代码不起作用res.redirect不起作用....

我是否必须为每个提取api编写重定向条件语句?

有没有一种方法可以直接从服务器重定向,而无需在客户端获取api中使用条件语句?

来人帮帮我 ...

编写中间件函数。 这是用于检查用户是否在使用Firebase的生态系统中登录的实现。

// Verify the user identity
const verifyoAuth = (req, res, next) => {

    const idToken = req.token || ''; // I get the token using BearerToken parser. 

    if( idToken == '' ){
        return returnQueryError(res, 401, "Unauthorized");
    }

    fbAdmin.auth().verifyIdToken(idToken).then( user => {

        req.user = user;

        next(); // resume to next route.

    }).catch( error => {

        // Report the incident
        eventsLogger.error( error );

        // Send back 401 for usr
        returnQueryError(res, 401, "Unauthorized");    

    });

}

并将其用于特定路线:

app.get('/api/:blah', verifyoAuth, (req, res, next) => {

    const { user } = req; // the `user` object would have some data about the authenticated user.

    // Return what data
    res.json({ msg: 'I am authenticated' })

})

暂无
暂无

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

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