【问题标题】:Downloading the file from server but still getting error 'Cannot fetch' and not going inside fetch.then function从服务器下载文件但仍然出现错误“无法获取”并且没有进入 fetch.then 函数
【发布时间】:2020-08-10 23:44:34
【问题描述】:

这是我从节点服务器下载文件时遇到的错误。

文件正在下载,但我提供的名称不正确,因为提取没有访问它的响应部分。

这是从节点服务器获取.pdf文件的下载文件函数。

downloadFileHandler = async (name, path) => {
this.setState({ cvDownloadLoading: true });
try {
  const response = await fetch(
    `${process.env.REACT_APP_SERVER_URL}/${path}`
  );
  if (!response.ok) throw response;
  const buffer = await response.arrayBuffer();
  const url = window.URL.createObjectURL(new Blob([buffer]));
  const element = document.createElement('a');
  element.style.display = 'none';
  element.href = url;
  element.setAttribute('download', name);
  document.body.appendChild(element);
  element.click();
  this.setState({ cvDownloadLoading: false });
  window.URL.revokeObjectURL(element.href);
  document.body.removeChild(element);
} catch (err) {
  this.setState({ cvDownloadLoading: false });
  if (err.name === 'AbortError') {
  } else {
    try {
      // const body = await err.json();
      console.log(err);
    } catch (e) {
      console.log('catch', e);
    }
  }
}

};

后端节点安装了“cors”,应用正在使用它。

const cors = require('cors');
app.use(cors());

并像这样静态地提供文件。

app.use('/data', express.static(path.join(__dirname, 'data')));

编辑: 现在我尝试下载图像文件,它下载没有任何问题。 这是 PDF 下载或任何不是图像的文件(可能)的问题。 谁能解释一下?

【问题讨论】:

  • 使用 npm start --host 0.0.0.0 运行你的 node js 代码
  • 我做了,但没有区别
  • 遇到同样的错误
  • 响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?

标签: node.js reactjs cors fetch


【解决方案1】:

我认为您必须配置您的 cors 设置并在源字段中添加您的客户端域。试试这样:

const corsOptions = {
   origin: 'http://localhost:8080'
};
// and then
app.use(cors(corsOptions));

您可以在此处的配置 CORS 部分中查看此示例 https://expressjs.com/en/resources/middleware/cors.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-26
    • 2021-10-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2019-08-15
    相关资源
    最近更新 更多