Search code examples
node.jsexpressfitbit

Can't catch the URL parameters with ExpressJS


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.


Solution

  • 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.