0

我正在生成一个 excel 文件,并希望通过使用 Next.js 框架触发 API 路由来为客户端下载它。我无法使用fetch触发下载。可以触发下载,window.open(//urlhere, '_self')但使用 fetch 的 API 调用会根据请求给出以下响应:

API resolved without sending a response for /api/download?Students= this may result in stalled requests.

文档说我们可以通过这样的excel4nodeAPI 发送一个 excel 文档:

// sends Excel file to web client requesting the / route
// server will respond with 500 error if excel workbook cannot be generated
var express = require('express');
var app = express();
app.get('/', function(req, res) {
  wb.write('ExcelFile.xlsx', res);
});
app.listen(3000, function() {
  console.log('Example app listening on port 3000!');
});

这是我的后端download.js,它位于pages/api/

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import Link from "next/link";
import getPartners from "../../components/main";
import excel from "excel4node";

export default function handler(req, res) {
  const students = req.query.Students.split(",");
  const partners = JSON.stringify(getPartners(students));
  let workbook = createExcelList(partners);
  workbook.write("PartnerList.xlsx", res);
}

const createExcelList = (partnersJSON) => {
  const workbook = new excel.Workbook();
  const partnersObject = JSON.parse(partnersJSON);
  
 /* Using excel4node a workbook is generated formatted the way I want */
  return workbook;
};

export const config = {
  api: {
    bodyParser: true,
  },
};

这是在前端按下按钮时触发的功能。

  const makePartners = async () => {
    let queryStudents = studentList.join(",");
    const url = "http://localhost:3000/api/download?Students=" + queryStudents;
    if (studentList.length !== 0) {
      try {
        const res = await fetch(url, {
          headers: {
            "Content-Type":
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          },
        });
        console.log(res);
      } catch (e) {
        console.log(e);
      }
    }
  };

这不会触发下载。但是使用window.open(url, '_self)确实如此。所以,我可以通过将函数更改为以下来触发下载。但是我认为这不是正确的做事方式,并且希望能够理解如何正确使用 fetch。

  const makePartners =  () => {
    let queryStudents = studentList.join(",");
    const url = "http://localhost:3000/api/download?Students=" + queryStudents;
    if (studentList.length !== 0) {
       window.open(url, "_Self");
    }
  };

我不确定这是否是 Next.js 问题。有没有人有任何见解?任何帮助,将不胜感激。

4

0 回答 0