返回下载文件的发布请求 [英] Post request that returns a download file
问题描述
我正在将数据发送到我的服务器,该服务器根据请求创建一个 pdf 文件,该文件创建正常,但我无法将文件发送回客户端.我正在使用 React 提交表单
I am sending data to my server that creates a pdf file based from the request, which is being created fine but I cant get the file to be sent back to the client. I am using React to submit the form
handleSubmit(event) {
event.preventDefault();
var body = {
id: this.state.id,
text: this.state.text
}
fetch('http://localhost:5000/pdf', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
},
}).then(function(file) {
window.open(file.url);
});
}
它的开放 http://localhost:5000/pdf,但因为我没有 GET 路线为此,没有什么可以下载.这是我的 POST 路线
Its opening http://localhost:5000/pdf, but since I don't have a GET route for it, nothing gets download. This is my POST route
router.post('/pdf', async function(req, res) {
var makePdf = require('./file-create/pdf.js');
makePdf(req, res);
});
并且文件被返回为 pdfDoc.pipe(res);
我不能只使用 GET 路由,因为我无法以这种方式发送数据,我如何才能将此文件发送到客户端?
I cant just use a GET route because I can't get data sent in with that way, how can I get this file to get sent to the client?
推荐答案
当您使用 window.open
时,您正在调用 GET 请求.这将在带有 URL 的新选项卡中打开 url.当您将其从 GET 更改为 POST 时,这将不起作用.
You're calling a GET request when you're using window.open
. This will open the url in a new tab with the URL. This won't work when you have changed it from GET to POST.
要解决此问题,您可以使用 downloadjs
(https://www.npmjs.com/package/downloadjs) 以允许您下载从服务器返回的 blob.
To get around this, you can use downloadjs
(https://www.npmjs.com/package/downloadjs) to allow you to download the blob that is returned from the server.
我在下面包含了一些示例代码.这包括带有获取请求的 index.html 文件和用于返回简单 pdf 的 server.js.
I've included some example code below. This includes the index.html file with the fetch request and the server.js for returning a simple pdf.
var body = {
id: 1,
text: 'hello world',
};
fetch('/download', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
},
}).then(function(resp) {
return resp.blob();
}).then(function(blob) {
return download(blob, "CUSTOM_NAME.pdf");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script>
var express = require('express');
var app = express();
app.post('/download', function(req, res){
res.download('./make-file/whatever.pdf');
});
app.listen(3000);
这篇关于返回下载文件的发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!