Skip to content

Create routes for authentication and use variable in another route #1120

@sunnykeerthi

Description

@sunnykeerthi

Hi,
This is not an issue, but a question
I'm building an express app that connects to JSforce using OAuth2. Currently when I have my code placed in a single file, it works fine. But I want to divide them into separate routes and use it.

my app.js is as below.

var express = require('express');
var path = require('path');
const jsforce = require('jsforce');
var indexRouter = require('./routes/index');
var app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

var oauth2 = new jsforce.OAuth2({
   loginUrl : 'https://login.salesforce.com',
    clientId : '<My_Client_ID>',
    clientSecret : '<My_Client_Secret>',
    redirectUri : '<My_Redirect_URL>'
  }); 

  app.get('/oauth2/auth', function(req, res) {
    res.redirect(oauth2.getAuthorizationUrl({ scope : 'api web full refresh_token offline_access' }));
  });
  
  app.get('/oauth/callback', function(req, res) {
    var conn = new jsforce.Connection({ oauth2 : oauth2 });
    var code = req.param('code');
    conn.authorize(code, function(err, userInfo) {
      if (err) { return console.error(err); }
      console.log("User ID: " + userInfo.id);
      console.log("Org ID: " + userInfo.organizationId);
       res.send('success');
    }); 
  });

This is perfectly working for me. i.e., I am able to console.log the details. But, I want to divide it into modules, like for e.g. app.use('/auth', authRouter);, In this, the authorization stuff should happen.

And I'll create another route /getAccounts, and the file will be /routes/getAccounts.js and I'll have the below code in that file.

var records = [];
conn.query("SELECT Id, Name FROM Account", function(err, result) {
  if (err) { return console.error(err); }
  console.log("total : " + result.totalSize);
  console.log("fetched : " + result.records.length);
})

here the conn used above should be conn from my auth. Please let me know how Can I do it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions