我最近开始涉足网络编程,并开始学习 NodeJS。现在有点不知所措,所以我想我可以在这里请求一个 启示。
基本上我的主要目标是创建一个页面,用户可以在其中输入特定数据并单击按钮。根据数据,用户将收到下载或警告,其中显示“无法下载文件”之类的内容。
我的 ajax 调用和其他东西工作正常。我有一个函数尝试创建一个文件并返回该文件的路径(或一个对象,其中包含错误消息)。但我不希望用户通过按钮“重新启动”该功能。
示例:用户填写数据并按下按钮。 ajax 调用发生并且函数启动。当用户在函数仍在运行时按下按钮时,整个过程将重新启动。我希望我的程序是这样的(必须在服务器端!)
-> 检查进程是否正在运行?
如果是 -> 警告消息“无法启动该进程”。
如果否 -> 启动该过程并返回下载或错误消息。
代码:
HTML 按钮:(注意;dataA
、dataB
、dataC
只是文本字段)
<input type="button" onclick="callServerSideScript('dataA','dataB','dataC')" value="Get Build" class="button">
客户端 JavaScript :
function callServerSideScript(dataA,dataB,dataC){
a = document.getElementById(dataA).value;
b = document.getElementById(dataB).value;
c = document.getElementById(dataC).value;
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', '/buildRequest')
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("firstData="+a+"&secondData="+b+"&thirdData="+c);
}
NodeJS/ExpressJS - 服务器端 JS(注意 - dbFunctions
是一个执行所有后端操作并尝试创建输出文件的函数。如果成功,它返回一个“路径字符串”;如果失败,它返回一个对象。
var express = require('express');
var bodyParser = require("body-parser");
var dbFunc = require("./dbFunctions.js");
var util = require('util');
var app = express();
var path = require('path');
var fs = require('fs');
var port = 8888;
//allow to use body-parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//allow to use static files
app.use(express.static("public"));
//listen to smth
app.post('/buildRequest', function (req, res) {
var main=dbFunc.main(req.body.firstData,req.body.secondData,req.body.thirdData,function(data) {
var result = data;
if(util.isString(result)){
//in this case the user would just reicive the download
console.log("result is string");
var filePath = result;
res.download(filePath);
}else{
//in this case the user should receive an alert containing a stringify of the object
console.log("result is not an string");
console.log(JSON.stringify(result));
}
});
});
//start server
app.listen(port);
console.log("Server running on port" + port);
我已经阅读了一些关于 res.download()
的内容,但不知何故下载不会出现。
也没有出现错误消息。
简单的 alert();
也不起作用(就像在客户端 JavaScript 中一样)。
希望我的代码是可以理解的并且您理解我的问题。
最佳答案
我建议您使用异步方法,这样您就可以使用简单的锁定方法来解决问题。
此外,请查看以下链接并向下滚动以查看 Gif 图像形式的结果,我想这就是您正在寻找的内容。
关于javascript - NodeJS 初学者问题。 "Create a download for a user"并避免多个相同的服务器调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49639052/