Angular无法使用res.download从Express获取文件下载

时间:2018-12-30 22:01:31

标签: javascript node.js express

在我的应用程序中,我在后端创建一个文件,然后希望通过浏览器下载将其交付给用户。我尝试了很多

这是快递后端:

app.get('/download', (req, res) => {
  res.download('filename.txt', function (err) {
    console.log(err);
  });
})

控制台调用没有返回,因此大概没有错误。这是我在前端所做的工作,遵循建议here和此处:

window.open('localhost:3000/download');

结果是我弹出一个空白窗口,但没有下载。我也尝试过this

const filePath = 'localhost:3000/download/';
const link = document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();

但是在这种情况下,什么也没有发生。

我在做什么错?我什至不知道如何进一步调试。

更新1

感谢@jal_a,我已经取得了进步。我现在意识到,如果我手动创建一个窗口并输入URL(如建议的那样),则下载工作正常。但是,使用url相同的window.open(url)从应用程序启动窗口时,窗口会打开,但不会启动下载。如果然后转到创建的窗口,请单击URL,然后按回车键……瞧!有用!如何从应用程序启动窗口启动下载?

更新2

感谢@IceMetalPunk,我尝试了这一点,并且在控制台中收到以下错误-我尝试下载的文件是gpx格式的gps数据-我可以在响应中看到,但似乎是期待JSON?我需要做任何预处理才能发送文件吗?:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", 
url: "http://localhost:3000/download/", ok: false, …}
error:
error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse 

...

text: "<?xml version="1.0" encoding="UTF-8"?>
↵<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/0">
↵   <rte>
↵      <name>undefined</name>
↵      <rtept lat="50.70373" lon="-3.07241" />
↵      <rtept lat="50.70348" lon="-3.07237" />
↵   </rte>
↵</gpx>"
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: 
ƒ}
message: "Http failure during parsing for http://localhost:3000/download/"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:3000/download/"
__proto__: HttpResponseBase

1 个答案:

答案 0 :(得分:0)

问题是我的下载链接没有包含this answer所描述的网址的In function ‘int fetchJD(std::__cxx11::string)’: astroapp.cpp:43:12: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘int’ in return return temp; 元素。