Skip to content

Commit 5ba688b

Browse files
authored
fix: improve no-cors request block error (#21902)
1 parent b3c067d commit 5ba688b

2 files changed

Lines changed: 13 additions & 3 deletions

File tree

packages/vite/src/node/server/middlewares/rejectNoCorsRequest.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,15 @@ export function rejectNoCorsRequestMiddleware(): Connect.NextHandleFunction {
2525
// we only need to block classic script requests
2626
req.headers['sec-fetch-dest'] === 'script'
2727
) {
28-
res.statusCode = 403
28+
// Send a JavaScript code instead of 403 so that the error is shown in the devtools
29+
// If we send 403, the browser will avoid loading the body of the response
30+
// and just show "Failed to load" error without the detailed message.
31+
res.setHeader('Content-Type', 'text/javascript')
2932
res.end(
30-
'Cross-origin requests for classic scripts must be made with CORS mode enabled. Make sure to set the "crossorigin" attribute on your <script> tag.',
33+
`throw new Error(${JSON.stringify(
34+
'[Vite] Cross-origin requests for classic scripts must be made with CORS mode enabled.' +
35+
' Make sure to set the "crossorigin" attribute on your <script> tag.',
36+
)});`,
3137
)
3238
return
3339
}

playground/fs-serve/__tests__/commonTests.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ test.runIf(isServe)(
495495
reject(e)
496496
})
497497
})
498-
expect(res.statusCode).toBe(403)
498+
expect(res.statusCode).toBe(200)
499499
const body = Buffer.concat(await ArrayFromAsync(res)).toString()
500500
expect(body).toContain(
501501
'Cross-origin requests for classic scripts must be made with CORS mode enabled.',
@@ -531,6 +531,10 @@ test.runIf(isServe)(
531531
})
532532
})
533533
expect(res.statusCode).not.toBe(403)
534+
const body = Buffer.concat(await ArrayFromAsync(res)).toString()
535+
expect(body).not.toContain(
536+
'Cross-origin requests for classic scripts must be made with CORS mode enabled.',
537+
)
534538
},
535539
)
536540

0 commit comments

Comments
 (0)