fetch api return 错误的响应对象

fetch api return wrong response object

我在 React js

中使用 fetch api 向我的后端服务器发送请求
const formData = new FormData();
    formData.append("image", file);
    formData.append("userId", currentUser.id);
    formData.append("sliderNumber", sliderNumber);

    const myHeaders = new Headers();
    myHeaders.append("Content-Type", file.type);
    myHeaders.append("Aceess-Control-Allow-Origin", "*");

    fetch("http://localhost:4000/upload/slide-image", {
      method: "POST",
      headers: myHeaders,
      mode: "no-cors",
      body: formData
    })
      .then(response => response)
      .then(data => console.log("Printing data: ", data));
  };

在长生不老药后端

def upload(conn, params) do
  # uploading code 

  #send response to the client with amazon s3 image url
  send_resp(conn, 200, image_url)
end

但是从 api 获取的响应对象是空的

Response {
  body: null
  bodyUsed: false
  headers: Headers {}
  ok: false
  redirected: false
  status: 0
  statusText: ""
  type: "opaque"
  url: ""
}

当我用状态码 400 响应时它并没有改变。

似乎 fetch api 在某些时候没有正确构建 Reponse 对象。因为我可以在浏览器网络选项卡中找到正确的状态代码和响应主体。但是 Response 对象不保存来自后端服务器的响应。

有什么想法吗?

你的Content-Type错了。将文件与其他数据一起发送时,Content-Type 仍应为 multipart/form-data

如果您希望从您的服务器收到文本响应,那么在您的第一个 .then(.. 上您应该这样做:

fetch("http://localhost:4000/upload/slide-image", {
      method: "POST",
      headers: myHeaders,
      mode: "no-cors",
      body: formData
    })
      .then(response => response.text()) // <--- 
      .then(data => console.log("Printing data: ", data));

fetch return 是一个解析为 Response 的 Promise。当你在这个阶段使用 .text() 时,你实际上做的是获取响应流,读取它完成和 return 一个将用文本解析的承诺。

除此之外,您还使用 mode: "no-cors"(正如其他用户在他们的回答中提到的那样)在很多方面限制了您。例如,即使您按照我上面的说明进行操作,您也会得到一个空字符串,即使您正尝试从您的服务器 return 某些内容。那将是因为这种模式。

您可以在项目符号 no-cors 下找到有关它的更多详细信息 here

 mode: "no-cors",

您将模式设置为 no-cors,因此响应是不透明的,这意味着您看不到它的内部。

如果您需要阅读回复,请不要这样做。


旁白:

myHeaders.append("Content-Type", file.type);

表单数据 object 的错误 content-type。不要设置 content-type。 fetch API 会自动设置正确的。

   myHeaders.append("Aceess-Control-Allow-Origin", "*");
您拼错的

Access-Control-Allow-Origin 响应 header,而不是请求 header.

.then(response => response)

原封不动地返回响应是毫无意义的。如果你得到一个普通的 URL,你可能想要 response.text()

接受的答案解决了我的问题。

如果您需要来自后端的 JSON 对象,请使用

.then((response) => response.json())