A
A
Alisa942019-02-01 08:10:00
JavaScript
Alisa94, 2019-02-01 08:10:00

How to pass a promise value from one file to another?

I have a bad situation. I use express and axios, I want to pass the value of the promise, but they just can't. There is a server file, authentication and baskets. I am getting an access token variable in a server file and have to pass it to the cart function. When everything is written in one file, there are no problems, when I write with a separate authentication file, there are no problems either, but when I write another separate basket file, then nothing comes out.
Server body file

const path = require('path');
const express = require('express');           // For web server
const Axios = require('axios');               // A Promised base http client
const bodyParser = require('body-parser');    // Receive JSON format
const querystring = require('querystring');

let app = express();
app.use(bodyParser.json())

app.use(express.static(path.join(__dirname, 'public')));

const config = require('./config');

const PORT = config.credentials.PORT; // import from bim start.js
var FORGE_CLIENT_ID = 'ZqbXzFL8NMXtovqJrLG0O9f5Ar3nQRoE';
var FORGE_CLIENT_SECRET = 'PM4vPHZGQArq99qn';
const scopes = 'data:read data:write data:create bucket:create bucket:read';

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.statusCode).json(err);
})

Authentication file
const path = require('path');
const express = require('express');
const Axios = require('axios');
const bodyParser = require('body-parser');
const querystring = require('querystring');        

const config = require('../config');

var FORGE_CLIENT_ID = 'ZqbXzFL8NMXtovqJrLG0O9f5Ar3nQRoE';
var FORGE_CLIENT_SECRET = 'PM4vPHZGQArq99qn';
const scopes = 'data:read data:write data:create bucket:create bucket:read';

let router = express.Router();
router.use(bodyParser.json());

module.exports = oauth => {
  return Axios({
      method: 'POST',
      url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
      headers: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: querystring.stringify({
        client_id: FORGE_CLIENT_ID,
        client_secret: FORGE_CLIENT_SECRET,
        grant_type: 'client_credentials',
        scope: scopes
      })
    })
  }

Continuing Authentication in Server File
let access_token = '';
var oauth = require('./routes/oauth')
app.get('/api/forge/oauth', function(req, res) {
  oauth()
  .then(function (response) {
      // Success
      // let's save token into the varible access_token
      access_token = response.data.access_token;
      console.log(response);
      console.log(access_token);
      // Then, the app is routed to, which creates a shared bucket for our app.
      res.redirect('/api/forge/datamanagement/bucket/create');
  })
    .catch(function (error) {
      // Failed
      console.error(error);
      res.send('Failed to authenticate');
    });
  });

Basket File
const path = require('path');
const express = require('express');
const Axios = require('axios');
const bodyParser = require('body-parser');
const querystring = require('querystring');        

const config = require('../config');

const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';
const policyKey = 'transient'; // Expires in 24hr


module.exports = bucketCreate => {
  return Axios({
    method: 'POST',
    url: 'https://developer.api.autodesk.com/oss/v2/buckets',
    headers: {
      'content-type': 'application/json',
      Authorization: 'Bearer ' + access_token
    },
    data: JSON.stringify({
      'bucketKey': bucketKey,
      'policyKey': policyKey
    })
  })
}

Continuation of the basket part in the server file
var bucketCreate = require('./routes/bucketCreate')
app.get('/api/forge/datamanagement/bucket/create', function (req, res) {
bucketCreate()
    .then(function (response) {
      // Success
      console.log(response);
      res.redirect('/api/forge/datamanagement/bucket/detail');
    })
    .catch(function (error) {
      if (error.response && error.response.status == 409) {
        console.log('Bucket already exists, skip creation.');
        res.redirect('/api/forge/datamanagement/bucket/detail');
      }
      // Failed
      console.log(error);
      res.send('Failed to create a new bucket');
    });
});

I am unable to pass the access_token value from the server file to the basket file, where further operations with them will take place. I also could not pass this variable to the authentication file, so I went around and got part of the authentication file in the server file, and performed manipulations with the access_token in the server file. Error code 401 (if I'm not mistaken, or 403). In any case, I would appreciate your help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Abcdefgk, 2019-02-01
@Alisa94

server.js

const path = require('path');
const express = require('express');           // For web server
const Axios = require('axios');               // A Promised base http client
const bodyParser = require('body-parser');    // Receive JSON format
const querystring = require('querystring');

// Set up Express web server
let app = express();
app.use(bodyParser.json());
// this line say of server, that we run server.js he open html file from public directory
app.use(express.static(path.join(__dirname, 'public'))); // it was static(__ + 'public or www')

// let's importing config.js file where are the configuration for dotenv/env and credentials_id/secret/url/PORT and scopes
const config = require('./config');

const PORT = config.credentials.PORT; // import from bim start.js
const scopes = 'data:read data:write data:create bucket:create bucket:read';


var oauth = require('./routes/oauth');
var bucketCreate = require('./routes/bucketCreate');

app.get('/api/forge/oauth', function(req, res) {
  oauth()
    .then(function (response) {
        // Success
        // let's save token into the varible access_token
        // Then, the app is routed to, which creates a shared bucket for our app.	
        var access_token = response.data.access_token;
        
        bucketCreate(access_token)
          .then(function (response) {
            // Success
            console.log(response);
            res.redirect('/api/forge/datamanagement/bucket/detail');
          })
          .catch(function (error) {
            if (error.response && error.response.status == 409) {
              console.log('Bucket already exists, skip creation.');
              res.redirect('/api/forge/datamanagement/bucket/detail');
            }
            // Failed
            console.log(error);
            res.send('Failed to create a new bucket');
          });
      })
      .catch(function (error) {
        // Failed
        console.error(error);
        res.send('Failed to authenticate');
      });
    });
    
    

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.statusCode).json(err);
});

// This is for web server to start listening to port 3000
app.listen(PORT, () => { 
  if (process.env.FORGE_CLIENT_ID == null || process.env.FORGE_CLIENT_SECRET == null) {
    console.log('*****************\nWARNING: Client ID & Client Secret not defined as environment variables.\n*****************');
  }
  console.log(`Server listening on port ${PORT}`);
});

oauth.js
/*
 * Authentication
 */
const Axios = require('axios');
const querystring = require('querystring');        

const config = require('../config');

module.exports = function() {
  return Axios({
    method: 'POST',
    url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: querystring.stringify({
      client_id: config.credentials.client_id,
      client_secret: config.credentials.client_secret,
      grant_type: 'client_credentials',
      scope: config.scopes.internal
    })
  });
};

backetCreate.js
/*
 * Bucket Creation
 */
const Axios = require('axios');
const config = require('../config');

// Prefix with your ID so the bucket key is unique across all buckets on all other accounts
const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';
const policyKey = 'transient'; // Expires in 24hr

  // Create an application shared bucket using access token from previous route
  // We will use this bucket for storing all files in this tutorial

module.exports = function(access_token) {
                        console.log('!!!!!!!!!!!!! ' + access_token);
  return Axios({
    method: 'POST',
    url: 'https://developer.api.autodesk.com/oss/v2/buckets',
    headers: {
      'content-type': 'application/json',
      Authorization: 'Bearer ' + access_token
    },
    data: JSON.stringify({
      'bucketKey': bucketKey,
      'policyKey': policyKey
    })
  });
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question