1

I'm trying to capture the parameter values from the callback URL coming from the Fitbit API.

The call back URL looks like below,

http://localhost:9000/callback#access_token=********&user_id=*******&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=30418415

I have stated by callback URL in the fitbit API as http://localhost:9000/callback.

My ExpressJS code is as below.

const express = require('express');
const morgan = require('morgan');
const path = require('path');

const app = express();


app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));


app.use(express.static(path.resolve(__dirname, '..', 'build')));


app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});

const PORT = process.env.PORT || 9000;

app.get('/callback', function(req, res) {
    var access_token = req.param('access_token') || null;
    var user_id = req.param('user_id') || null;

    res.send(access_token + ' ' + user_id);
});

app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}!`);
});

I can't figure out where the problem is.

kokilayaa
  • 579
  • 4
  • 7
  • 19

2 Answers2

1

The # symbol in an URL is to introduce framgent identifier. So your callback url http://localhost:3000/callback#access_token=********&user_id=*******&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=30418415 will only get the http://localhost:3000/callback not sending any parameters to your server. So, you can not get these parameters in your server directly.

However there is solution to this. Please refer to this answer.

Tolsee
  • 1,695
  • 14
  • 23
0

req.param('token') is depreciated use req.params.token pass the value directly into the url

if you are using req.params specify you key params in the url

   app.get('/callback/:access_token/:user_id', function(req, res) {
   //url ==> localhost:9000/callback/1233/123
    var access_token = req.params.access_token || null;
        var user_id = req.params.user_id || null;
           console.log(req.params)
        res.send(access_token + ' ' + user_id);
    });

if you want the catch the value in the url means use req.query instead of req.params pass the value using the key of req.query

app.get('/callback',function(req, res) {
    var access_token = req.query.access_token || null;
    var user_id = req.query.user_id || null;
    console.log(req.query);
    res.send(access_token + ' ' + user_id);
});