首页 > 解决方案 > Node.JS 获取/发布

问题描述

我的脚本打算将记录在用户计算机上的音频作为 blob 发送到服务器并将其作为文件写入。但是,这不会发生,我什至没有得到回复。相反,它超时:

发布https://example.com:8080/upload net::ERR_CONNECTION_TIMED_OUT 。

Uncaught (in promise) TypeError: Failed to fetch

什么可能导致此问题?

客户端:

async function sendData(data) {


  timestamp = String(Date.now());
  fileName = timestamp.concat('.wav');
  console.log(fileName);
  Shiny.onInputChange("file_name", fileName);
  
  let formdata = new FormData() ; //create a from to of data to upload to the server
  formdata.append(timestamp, data,  fileName); // append the sound blob and the name of the file. third argument will show up on the server as req.file.originalname

  // Now we can send the blob to a server...
  var url = 'https://www.example.com:8080/upload'; //we've made a POST endpoint on the server
    
  // Default options are marked with *
const res = await fetch(url, {
  method: 'POST',
  cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  headers: {
    'enctype': 'multipart/form-data'
  },
  body: formdata // body data type must match "Content-Type" header
});
return res; 
} 

function handlerFunction(stream) {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
  audioChunks.push(e.data);
  if (rec.state == "inactive") {
    let blob = new Blob(audioChunks,{type:'audio/mpeg-3'});
    sendData(blob).then(blob => {
      console.log(blob); 
    });
  }
};
}

服务器端:

const express = require('express'); //make express available
const app = express(); //invoke express
const multer  = require('multer') //use multer to upload blob data
const upload = multer(); // set multer to be the upload variable (just like express, see above ( include it, then use it/set it up))
const fs = require('fs'); //use the file system so we can save files

app.post('upload', upload.single('data'), function (req, res, next) {
  // console.log(req.file); // see what got uploaded

  let uploadLocation = __dirname + req.file.originalname // where to save the file to. make sure the incoming name has a .wav extension

  fs.writeFileSync(uploadLocation, Buffer.from(new Uint8Array(req.file.buffer))); // write the blob to the server as a file
  res.sendStatus(200); //send back that everything went ok

})

//makes the app listen for requests on port 8080
app.listen(8080, function(){
  console.log("app listening on port 8080!")
})

标签: javascriptnode.js

解决方案


推荐阅读