【发布时间】:2020-08-26 16:24:16
【问题描述】:
到目前为止,我在 SO 上阅读的其他解决方案都没有奏效,所以请多多包涵。
我在 React 中有一个前端,用户在其中向后端发送文件下载请求以及一些变量:
const data = text.value;
fetch("http://localhost:4000/dl", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data,
file: filetypes.selected,
}),
}).then((res) => {
...???...
});
data 变量是一些 JSON,例如:{"arrowParens": "always"}。
file 变量包含要下载的文件名:.prettierrc。
我的后端在 NodeJs/express 中,并像这样处理请求:
index.ts:
app.use("/dl", getFile);
getFile.ts:
import appRoot from "app-root-path";
const index = async (req: Request, res: Response) => {
const { data, file } = req.body;
// download file if folder exists
if (fs.existsSync(`${appRoot}/tmp/${file}`)) {
res.sendFile(
".prettierrc",
{
dotfiles: "allow",
headers: {
"Content-Type": "json",
},
root: path.join(__dirname, "../tmp"),
}
);
}
};
我从服务器得到了正确的响应:POST /dl 200 11.878 ms - 55 但文件没有下载,所以我想我必须有一些额外的代码。我读过另一篇文章,其中 OP 创建了一个锚标记,并将 href 设置为 blob url,但这似乎不起作用,因为响应没有显示 URL。我不得不选择POST 请求,因为我必须发送那些决定文件的变量。不确定方法是否在这里有所作为。
如何让浏览器提示下载我的.prettierrc 文件?我错过了什么?
【问题讨论】:
标签: javascript node.js reactjs express