【发布时间】:2017-09-26 11:08:56
【问题描述】:
我正在尝试制作一个程序,提示浏览器端的用户从 nodeJS 服务器下载文件。我读到了 expressJS 函数 res.dowload,但我想我在客户端缺少一些东西,因为我没有下载任何文件,也没有提示我去哪里下载。
这是 NodeJS 代码:
var http = require("http")
var express = require("express")
var url = require("url")
var fs = require("fs")
var app = express();
app.get('/', function(req, res) {
console.log(req.url);
res.sendFile( __dirname + "/index.html");
})
app.get('/index1.html', function(req, res){
console.log(req.url);
res.send("Riko");
//res.sendFile( __dirname + "/index1.html");
});
app.get('/index1.html-download', function(req, res){
console.log(req.url);
res.sendFile(__dirname + "/download.txt");
});
app.listen(80, function(){
console.log('Server running at http://127.0.0.1:80/');
});
这是浏览器代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo"/>
<h2 id="header2">Hello</h2>
<button id="ajaxButton">Make a request!</button>
<button id="download">Download</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ajaxButton").click(function(){
$.get("index1.html", function(data, status){
console.log("Data: " + data + "\nStatus: " + status);
$("#header2").text(data);
});
});
//==
$("#download").click(function(){
$.get("index1.html-download", function(data, status){
console.log("Data: " + data + "\nStatus: " + status);
$("#header2").text(data);
});
});
//==
});
</script></body>
</html>
**** 编辑 ****
它是这样工作的:
app.get('/index1.html-download', function(req, res){
console.log(req.url);
res.download(__dirname + '/download.txt', 'download.txt', function(err){
if (err) {
console.log(err);
}
else {
console.log("File send without errors!");
}
});
});
【问题讨论】:
标签: javascript node.js browser frontend backend