在索引.html和应用.js [node.js] 之间共享变量

Share variables between index.html and app.js [node.js]

本文关键字:js node 之间 共享变量 html 应用 索引      更新时间:2023-09-26
//index.html
var audioCtx = new AudioContext();
var mySampleRate = audioCtx.sampleRate;
//app.js
var fileWriter = new wav.FileWriter(n + '.wav', {
    channels: 1,
    sampleRate: mySampleRate,
    bitDepth: 16
  });

我想与节点共享索引.html的 de mySampleRate [值].js 服务。我该怎么做?

首先,您需要在节点服务器中创建服务方法。

Express 是一个流行的框架,简化了这个过程。

var app = require( "express" )(),
    bodyParser = require( "body-parser" );
app.use( bodyParser.json() );
app.post( "/rate", function( req, res ) {
    console.log( req.body.rate );
} );

在客户端上,浏览器提供了一个API,用于通过一个名为XMLHttpRequest的对象向服务器发出HTTP请求,但你可以选择像superagent这样的东西,以获得更好的API和更一致的整个浏览器实现。

它应该看起来像这样:

var audioCtx = new AudioContext(),
    mySampleRate = audioCtx.sampleRate;
request
    .post( "/rate" )
    .send( { rate: mySampleRate } )
    .end( function( err, res ){
        if ( res.ok ) {
            console.log( "yey" );
        } else {
            console.log( "ney..." + res.text );
        }
    } );