在 React.Js 中使用 http-proxy-middleware 时无法从 api 获取图像

IT技术 reactjs proxy fetch http-proxy-middleware
2022-07-10 00:02:55

根据视频教程https://www.youtube.com/watch?v=hxyp_LkKDdk ,我在使用 http-proxy-middleware 时遇到了 cors 错误并修复了它(跳至解决方案:20:08,我已关注,如下所示)。一切都很好,直到我从 api 得到图片。我错过了什么?

这是我的 setupProxy.js

const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  
  // GET Image
  app.use(
    "/file/",
    createProxyMiddleware({
      target: "https://.....",
      changeOrigin: true,
    })
  );
};

和 user.js

const loadImage = () => {
    setLgShow(true);

    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Bearer abcdefghiklm");
    myHeaders.append("Content-Type", "application/json");

    var requestOptions = {
      method: "GET",
      headers: myHeaders,
      redirect: "follow",
    };
    fetch(`/file/${user.img_front_file_id}`, requestOptions)
      .then((response) => response.text())
      .then((result) => {
        console.log(result);
        imagRef.current = result;
        console.log(JSON.parse(result));
      })
      .catch((error) => console.log("error", error));
  };

和二进制垃圾(我调用 API 图像时的响应) 在此处输入图像描述

我终于找到了答案

const res = await axios({ url: `/file/${user.img_front_file_id}`, method: "GET", headers: { Authorization: "Bearer eFS3oJaQhRU1c5EajQUL", "Content-Type": "application/json", }, responseType: "blob", }); 

const file = new Blob([res.data], { type: "image/jpg" }); 

const url = URL.createObjectURL(file); imagFontRef.current = url;

setFinishFront(true); console.log(res);

0个回答
没有发现任何回复~