How can I use passportjs and reactjs together?

后端 未结 4 1749
旧巷少年郎
旧巷少年郎 2021-02-05 08:06

I have 3 views, (Home, signup, login)made in reactJs, I want to use passport in my project but I dont know how to do it, I have passport configurated and it url is working.

4条回答
  •  星月不相逢
    2021-02-05 09:09

    you need to create a middleware function where put the code

    function ensureAuthenticated(req, res, next){
      if(req.isAuthenticated()) { 
        return next() 
      } else {
        res.redirect('/')
      }
    }
    

    and then use in a router

    app.get('/account', ensureAuthenticated, function(req, res){
      // here return some data
    })
    

    From React probably you have to do a fetch request

    fetch('https://your_url/account', {
      credentials: 'include'  
    })
    

    Something like this, you have to make ajax request to the server or by using socket.io or websockets

提交回复
热议问题