[英]Empty Response headers received from WebAPI
我在前面使用 ASP.NET WebApi 和 ReactJs 应用程序,我正在创建一个 Get 方法来从服务器下载文件,并且我尝试在响应标头中设置 Content-Type 和 Content-Length:
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(bytes));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = bytes.Length;
当我使用如下 fetch 方法从 ReactJs 应用程序调用此方法时:
await fetch(`someservice/${clientid}/download/${fileName}`, { responseType: "arraybuffer" })
.then((response) => {
const reader = response.body.getReader();
//get total length
const contentLength = response.headers.get('Content-Length');
console.log(response.headers);
//read the data
let receivedLength = 0; // received that many bytes at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while (true) {
const { done, value } = reader.read();
if (done) {
break;
}
console.log(value);
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`)
}
//concatenate chunks into single Uint8Array
let chunksAll = new Uint8Array(receivedLength);
let position = 0;
for (let chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length;
}
});
我收到了没有 Content-Type 和 Content-Length 标头的响应:
但是 Content-Type 和 Content-Length 不是有效的标头吗?
fetch api JavaScript 中的响应标头已实现为迭代器,而不是 object,您可以尝试在下面访问标头:-
for (var header of respone.headers.entries()) {
console.log(header);
}
循环中的每个 header 项目将是一个字符串数组,其中第一个元素是键,第二个元素是值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.