Javascript 获取api返回错误的响应对象
我正在使用React js中的FetchAPI将请求发布到后端服务器Javascript 获取api返回错误的响应对象,javascript,fetch-api,Javascript,Fetch Api,我正在使用React js中的FetchAPI将请求发布到后端服务器 const formData = new FormData(); formData.append("image", file); formData.append("userId", currentUser.id); formData.append("sliderNumber", sliderNumber); const myHeaders = new Headers(); myHead
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
但来自fetch api的响应对象为空
Response {
body: null
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
}
当我回复状态代码400时,它不会改变
在某种程度上,fetchapi似乎没有正确地构建响应对象。因为我可以在浏览器网络选项卡中找到正确的状态代码和响应正文。但响应对象不包含来自后端服务器的响应
你知道吗?你的内容类型不对。当与其他数据一起发送文件时,内容类型仍应为多部分/表单数据。如果您希望从服务器收到文本响应,请先发送。然后。。你应该喜欢: fetchhttp://localhost:4000/upload/slide-形象,{ 方法:邮寄, 标题:myHeaders, 模式:无cors, 正文:formData } .thenresponse=>response.text//console.log打印数据:,数据; fetch返回一个解析为的承诺。当您在这个阶段使用.text时,您实际上要做的是获取响应流,将其阅读到完成,然后返回一个承诺,该承诺将通过文本解析 除此之外,您还可以使用mode:no cors,正如其他用户在回答中提到的那样,这在很多方面限制了您。例如,即使您按照上面的说明操作,也会得到一个空字符串,即使您试图从服务器返回一些内容。这将是因为这种模式 你可以在bullet no cors下找到更多细节 您将模式设置为no cors,因此响应是不透明的,这意味着您无法看到其中的内容 如果需要阅读回复,请不要这样做 旁白: 这是表单数据对象的错误内容类型。不要设置内容类型。fetch API将自动设置正确的API 您错误拼写的Access Control Allow Origin是响应头,而不是请求头
返回未更改的响应是毫无意义的。如果要返回普通URL,您可能需要response.text。接受的答案解决了我的问题 如果希望从后端获得JSON对象,请使用
.then((response) => response.json())
您是否希望从服务器收到JSON响应?当您使用模式:no cors时,不允许您指定的所有头。查看更多信息。因为在头文件中您允许cors,我想您可能是想删除模式:无cors位。另外,您可能是指.thenresponse=>response的其他内容。
myHeaders.append("Content-Type", file.type);
myHeaders.append("Aceess-Control-Allow-Origin", "*");
.then(response => response)
.then((response) => response.json())