Вообще, Axios - довольно забавный тип, в нем можно устанавливать "заголовки по умолчанию".
И как не странно, это работает и на сервере.
Вот такой, допустим, файл server.js
const path = require('path');
const express = require('express'); // For web server
const bodyParser = require('body-parser'); // Receive JSON format
const querystring = require('querystring');
// Set up Express web server
var 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 indRouter = require('./routes/indRouter');
indRouter(app);
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}`);
});
В папке routes лежить вот такой файл indRouter.js
var oauth = require('./oauth');
var bucketCreate = require('./bucketCreate');
var Axios = require('axios');
var publ = require('./publ');
var detail = require('./detail');
module.exports = function(app) {
app.get('/api/forge/oauth', function (req, res) {
oauth()
.then(function (response) {
// Success
var access_token = response.data.access_token;
Axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
//console.log(response);
res.redirect('/api/forge/datamanagement/bucket/create');
})
.catch(function (error) {
// Failed
console.log(error);
res.send('Failed to authenticate');
});
});
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');
});
});
app.get('/api/forge/oauth/public', function (req, res) {
// Limit public token to Viewer read only
publ()
.then(function (response) {
// Success
//console.log(response);
res.json({ access_token: response.data.access_token, expires_in: response.data.expires_in });
})
.catch(function (error) {
// Failed
console.log(error);
res.status(500).json(error);
});
});
app.get('/api/forge/datamanagement/bucket/detail', function (req, res) {
detail()
.then(function (response) {
// Success
console.log(response);
res.redirect('/upload.html');
})
.catch(function (error) {
// Failed
console.log(error);
res.send('Failed to verify the new bucket');
});
});
};
И рядом с ним лежат файлы
oauth.js
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
})
});
};
bucketCreate.js
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() {
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
})
});
};
publ.js
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: 'viewables:read'
})
});
};
detail.js
var 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';
module.exports = function() {
return Axios({
method: 'GET',
url: 'https://developer.api.autodesk.com/oss/v2/buckets/' + encodeURIComponent(bucketKey) + '/details',
//headers: {
//Authorization: 'Bearer ' + access_token
//}
});
};
В первом обработчике (файл indRouter.js) установлен заголовок по умолчанию Authorization с токеном
и больше его нигде писать не надо - он уже во всех запросах от Axios есть.