S
S
Stepgor2019-01-02 12:02:11
Node.js
Stepgor, 2019-01-02 12:02:11

How to correctly implement a post request with a subsequent redirect to the next page?

After logging in, the client gets to the callback page, where I make an api request to the key and then redirect to /auth, but I want to do auth on a post request, because there I get the client's data and enter it in the database, and then redirect to /

app.get('/callback', (req,res) => {
    request({
      headers: {
          'Authorization': 'Basic ' + usernamePasswordToBase64('id', 'secret'),
      },
      'url': 'url',
      "formData":{
          "grant_type": "authorization_code",
          "code": req.query.code,
      },
      "method": "POST"

    }, function(err,resp,body){

      if(err) console.log(err);

      // set the session so we are logged in
      req.session.authentication_data = body;
      res.redirect('/auth');
              
  })

})

Here is the auth
app.post('/auth', (req, res) => {
    var authentication_data = JSON.parse(req.session.authentication_data);
    request({
        url: 'url,
        headers: {
            'Authorization': 'Bearer ' + authentication_data.access_token,
        },
        method: 'GET'
      }, function (err, resp, body) {
        if (err) console.log(err)

        console.log(body);

        data = JSON.parse(body);
      
        userObj = {
          id: data.response.id,
          nickname:  data.response.username,
          avatarImg: data.response.avatar,
          balances: {
            usd: data.balance,
            coins: data.credits
          }
        }
        
        req.session.info = userObj;
        res.redirect('/');
      })
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2019-01-04
@yapaha

You can not do a redirect, but just put everything in "app.post('/auth', (req, res) => {..." into a separate method and call this method in "/callback"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question