从服务器脚本获取变量到客户端脚本

这是我目前正在努力解决的问题。我在一个 webapp 项目中,其中有 2 个脚本:

  • 一个被调用的脚本start.js,我在其中初始化服务器并初始化一个变量token. 这个脚本在我启动 webapp 时运行。

  • 调用的脚本viewer.js初始化查看器。该查看器需要前一个token才能工作。

我无法从客户端生成令牌,因为它需要 NodeJS,据我所知 NodeJS 在客户端不起作用。

我曾尝试使用全局变量、全局方法或 HTTP 请求,但到目前为止这些方法似乎都不起作用。关于如何做到这一点的任何提示?

这是我尝试过的:

// start.js

const ForgeSDK = require('forge-apis');

const express = require('express');

const path = require('path');

var app = express();

app.use('/static', express.static(__dirname + '/static'));


/**

 * Token generation

 */


oAuth2TwoLegged.authenticate().then(function(credentials){

    setToken(credentials.access_token)

}, function(err){

    console.error(err);

});

function setToken(newToken) {

    console.log("Definition du nouveau token")

    token = newToken;

    console.log(token)

};


app.get('/', function(req, res) {

    res.sendFile(path.join(__dirname + '/index.html')); 

});

app.listen(3000, function () {

    console.log('Token provider listening on port 3000')

});

// viewer.js

var token = '';

/**

 * Viewer initialization

 */


繁花如伊
浏览 168回答 1
1回答

蝴蝶不菲

您可以将回调传递给您的配置选项以获取令牌(通常通过 ajax)到请求:var options = {&nbsp; &nbsp; env: 'AutodeskProduction',&nbsp; &nbsp; getAccessToken: function(onGetAccessToken) {&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; // TODO: Replace static access token string below with call to fetch new token from your backend&nbsp; &nbsp; &nbsp; &nbsp; // Both values are provided by Forge's Authentication (OAuth) API.&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; // Example Forge's Authentication (OAuth) API return value:&nbsp; &nbsp; &nbsp; &nbsp; // {&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; "access_token": "<YOUR_APPLICATION_TOKEN>",&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; "token_type": "Bearer",&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; "expires_in": 86400&nbsp; &nbsp; &nbsp; &nbsp; // }&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; &nbsp; var accessToken = '<YOUR_APPLICATION_TOKEN>';&nbsp; &nbsp; &nbsp; &nbsp; var expireTimeSeconds = 86400;&nbsp; &nbsp; &nbsp; &nbsp; onGetAccessToken(accessToken, expireTimeSeconds);&nbsp; &nbsp; }}&nbsp;Autodesk.Viewing.Initializer(options, function onInitialized(){&nbsp; ...有关详细信息,请参见此处。并查看此处和此处创建一个端点以在您的 Node 后端生成访问令牌。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript