简体   繁体   中英

from fetch api in react to express res.redirect

I searched for a long time, but I could not find the answer.

When someone requests data from an api, fetch or ajax ( in SPA react )

I want to send data to only the logged in or authenticated user,

if not logged user or not authenticated user,

I would like to redirect to 'someReAuthPage'

My strategy is as follows.

in SPA react client

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

in express server

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')
}

but this code not working res.redirect not working....

Do I have to write a redirect conditional statement for every fetch api?

Is there a way to redirect directly from the server without using conditional statement in client fetch api???

somebody help me ...

Write a middleware function. Here's my implementation for checking if the user is logged in in an ecosystem where I use 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");    

    });

}

And to use it with a particular route:

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' })

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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