javascript - 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!")
})
解决方案
推荐阅读
- prolog - 列表 Prolog 列表的第一个元素
- postgresql - Microsoft Azure PostgreSQL 事件触发器与超级用户
- php - json 响应中收到的额外字符
- java - 在加法之前将 double 转换为 BigDecimal 是否足以保持原始精度?
- php - 如何覆盖重定向的响应正文?
- python - 关于 Keras 中的默认权重初始化器有什么解释吗?
- php - 如何通过在 PHP 中删除表来修复 SQL 错误?
- vaadin - 如何在 Vaadin 12 中创建 Web 服务?
- excel - 使用 VBA 在表单中调用工作表
- powerbi - 测量以跨多列计数