【发布时间】:2020-10-26 08:01:18
【问题描述】:
我在 Node.JS 服务器上工作,使用 Express 根据用户输入生成和下载 PDF。我使用 Axios POST 调用服务器,然后期望使用 Express 的 response.download() 下载文件。我最近从使用 <form action=""> 调用我的 API 的方法更改为 Axios,因为 Netlify 似乎不支持 NuxtAPI。该程序在旧版本中生成了所需的文件,但是对 Axios 的更改意味着它不再有效。
现在,没有文件被下载(即使是固定路径的文件,例如已发布网站上的文件),并且在提示下载之前页面正在重新加载。
我的代码如下:
print.vue:
<template>
<main>
<button class="btn btn-primary" @click="submit">Print Certificate</button>
</main>
</template>
<script>
export default{
methods:{
async submit(){
try{
let params = {
name: this.name,
kana: this.kana,
rank: this.rank,
date: this.date
}
// produces valid object in all cases
await this.$axios.$post('/api/certificate', null, {params})
}catch(err){
console.log(err)
alert(err)
}
}
},
computed:{ // functions from route params, resolve to these always for test case
name: function(){return 'Test Student'},
kana: function(){return "Tesuto Sutuudento"},
rank: function(){return "8th Kyu"},
date: function(){return '26th October, 2020"}
}
}
</script>
/api/certificate.js
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/', urlencodedParser, function(req, res) {
let response = {
name: req.query.name,
kana: req.query.kana,
rank: req.query.rank,
date: req.query.date
}
console.log(response)
html = html.replace("{{name}}", response.name)
html = html.replace("{{kana}}", response.kana)
html = html.replace("{{rank}}", response.rank)
html = html.replace("{{date}}", response.date) // always produces valid string (template)
pdf.create(html, options).toFile('static/certificates/' + response.name.split(' ')[0] + '_' + response.rank.split(' ')[0] + '_' + response.rank.split(' ')[1] + '.pdf', function(err, rep){
// file made with no difficulties
if (err) return console.log(err);
console.log(rep.filename) // gives absolute path (C:\\)
//res.download('https://get.pxhere.com/photo/computer-screen-technology-web-internet-signage-page-coding-website-html-programming-font-design-text-digital-information-java-site-games-software-development-code-screenshot-data-script-www-css-computer-programming-web-developer-web-development-programming-code-web-page-website-development-670370.jpg') // test fixed path downloading
//res.download(rep.filename,'my_pdf.pdf') // what I think the easiest solution should be
res.download('static/certificates/' + response.name.split(' ')[0]
+ '_' + response.rank.split(' ')[0] + '_'
+ response.rank.split(' ')[1] + '.pdf') // what worked before
})
})
总的来说,我对 API 和 Node 比较陌生,所以我缺少一些基本的东西吗?
【问题讨论】:
-
我想你可以使用
fs节点的模块,它非常完整,并使用fs.writeFileSync函数以 pdf 或任何格式写入数据 nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options -
您的表单看起来如何?听起来页面已重新加载,因为在客户端执行了默认操作。如果您使用
curl或邮递员之类的工具来生成 http 请求,您的服务器端代码是否有效? -
@Marc 没有使用表单,尽管它今天早上停止重新加载。所有数据都是从 URL 参数计算出来的
-
“this.name”在哪里定义?你的“
-
@Marc this.name 等是基于路由参数的 Nuxt 计算属性。我已将代码包含为简单地返回他们为我的测试用例解析的内容。我已编辑以包含相关标记
标签: javascript node.js express nuxt.js