簡體   English   中英

使用nodejs捕獲錯誤消息下載文件

[英]Capturing the error message downloading file with nodejs

我正在從 nodejs 下載一個文件。

當后端出現錯誤時,我需要向前端發送消息。

我的問題是我無法捕獲該消息。

我知道在后端使用 blob 和 json 存在一些問題。

但是我沒有解決。

我的代碼:

console.log(error.response.data.message)

總是返回“未定義”

//front end
    try{
        let response = await axios.post('/generateLoteXMLZIPConsulta');
        let blob = await new Blob([response.data], {
          type: "application/zip",
        });
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = window.URL.createObjectURL(blob);
        const fileName = response.headers["content-disposition"].match(
          /filename=(.*)/
        )[1];
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }catch(error){
      console.log(error.response.data.message)
    }
         //backend nodejs
         router.post("/generateLoteXMLZIPConsulta", async (req, res) => {
            ....
            ....
            try
               res.download(
                    path.resolve(__dirname, "../../file.zip"),
                    "xmlFile.zip"
            );
            catch (error){
               res.removeHeader("Content-disposition");
               res.status(400).json({ message: "You got an error" });
            }
        })      

首先,您的代碼中有一些錯誤:

...
  try {
    // you have to tell axios how to handle response with `responseType`
    let response = await axios.post('/generateLoteXMLZIPConsulta');

    // no need to use await here
    let blob = await new Blob([response.data], {
      type: "application/zip",
    });

    const link = document.createElement("a");

    // no need since you didn't append this element into DOM
    link.style.display = "none";

    link.href = window.URL.createObjectURL(blob);
    const fileName = response.headers["content-disposition"].match(
      /filename=(.*)/
    )[1];
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  } catch (error) {
    console.log(error.response.data.message)
  }
...

這是我的重現代碼:

// backend

app.post('/foo', async (req, res) => {
  try {
    // throw 'Something went wrong'
    res.download(path.resolve('bar.zip'))
  } catch {
    res.status(400).json({ message: 'You got an error' })
  }
})
// frontend

;(async function () {
  try {
    // with blob response you have no need to wrap response data to create blob again
    // {} is required otherwise axios will treat { responseType } as data
    let response = await axios.post('/foo', {}, { responseType: 'blob' })
    let blob = response.data
    console.log(window.URL.createObjectURL(blob))
  } catch (error) {
    console.log(error.response.data)
  }
})()

到目前為止,這是有效的,除非后端拋出錯誤,axios 會將響應視為我們設置的 blob。 所以我們必須將其轉換回 json。

axios.interceptors.response.use(null, async error => {
  if (error.response.request.responseType === 'blob') {
    // you may need to add an error handler if the response is not JSON
    error.response.data = await new Promise(resolve => {
      let reader = new FileReader()
      reader.addEventListener('load', () => {
        resolve(JSON.parse(reader.result))
      })
      reader.readAsText(error.response.data)
    })
  }
  throw error
});

這是相關的 Github問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM