Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit393e8de

Browse files
authored
Merge pull request#31 from xibai2sike/main
Correct handling of blob data
2 parents39259f7 +682fb13 commit393e8de

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

‎src/interceptor/fetch.ts‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -277,13 +277,45 @@ export default class FetchInterceptor extends Base{
277277
conststatus=mockItem.status;
278278
conststatusText=HTTPStatusCodes[status]||'';
279279

280-
constheaders=typeofHeaders==='function'
281-
?newHeaders({ ...mockItem.headers,'x-powered-by':'http-request-mock'})
282-
:Object.entries({ ...mockItem.headers,'x-powered-by':'http-request-mock'});
280+
const[headers,contentType]=(()=>{
281+
constdefaultContentType='application/json';
282+
if(typeofHeaders==='function'){
283+
constheaders=newHeaders({ ...mockItem.headers,'x-powered-by':'http-request-mock'})
284+
return[headers,headers.get('content-type')||defaultContentType]asconst;
285+
}
286+
constheaders=Object.entries({ ...mockItem.headers,'x-powered-by':'http-request-mock'});
287+
return[headers,headers.find(item=>item[0]==='content-type')?.[1]||defaultContentType]asconst;
288+
})()
283289

284-
constbody=typeofBlob==='function'
285-
?newBlob([typeofdata==='string' ?data :JSON.stringify(data)])
286-
:data;
290+
// 根据 content-type 判断 data 类型
291+
constbody=(()=>{
292+
if(contentType.includes('application/json')){
293+
constjsonStr=typeofdata==='string' ?data :JSON.stringify(data);
294+
returntypeofBlob==='function'
295+
?newBlob([jsonStr],{type:'application/json'})
296+
:jsonStr;
297+
}elseif(contentType.includes('application/octet-stream')||contentType.includes('image/')||contentType.includes('application/pdf')){
298+
// 处理为 Blob 类型,确保 data 为可用类型
299+
letblobPart:BlobPart;
300+
if(typeofdata==='string'||datainstanceofArrayBuffer){
301+
blobPart=data;
302+
}elseif(datainstanceofUint8Array){
303+
// 确保为标准 ArrayBuffer
304+
blobPart=data.bufferinstanceofArrayBuffer ?data.buffer :newUint8Array(data).buffer;
305+
}else{
306+
blobPart=typeofdata==='object' ?JSON.stringify(data) :String(data);
307+
}
308+
returntypeofBlob==='function'
309+
?newBlob([blobPart],{type:contentType})
310+
:blobPart;
311+
}else{
312+
// 默认处理为字符串
313+
conststr=typeofdata==='string' ?data :JSON.stringify(data);
314+
returntypeofBlob==='function'
315+
?newBlob([str],{type:'text/plain'})
316+
:str;
317+
}
318+
})()
287319

288320
if(typeofResponse==='function'){
289321
constresponse=newResponse(bodyasBodyInit,{ status, statusText, headers});

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp