File download via link #838
-
Hey. My API provides an endpoint for a simple file download. Its behavior is just the one from the binary response recipe. In my app I just have simple links pointing to the endpoint like Best regards, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, @micha149. The request your link makes is a navigation request. Such navigation requests are bypassed by design: Lines 246 to 249 in 3ea2534 Intercepting navigation requests may lead to all sorts of unpredictable behavior and must be avoided alongside static assets interception (like the initial HTML/CSS/JS of the page). I can also see that what you're doing is navigating to a resource in the next tab. This may prompt the download (depending on the response), but that's not the only way to initiate an in-browser download. SolutionTo control the downloaded binary in MSW, consider making a import download from 'downloadjs'
export default function Home() {
const handleDownload = () => {
fetch('/resource').then((blob) => {
download(blob, 'file.txt')
})
}
return (
<div>
<button onClick={handleDownload}>Download me</button>
</div>
)
} // handlers.js
import { rest } from 'msw'
export const handlers = [
rest.get('/resource', (req, res, ctx) => {
const content = 'hello world'
return res(
ctx.set({
'Content-Disposition': 'attachment',
'Content-Length': content.length,
}),
ctx.text(content)
)
}),
] |
Beta Was this translation helpful? Give feedback.
Hey, @micha149.
The request your link makes is a navigation request. Such navigation requests are bypassed by design:
msw/src/mockServiceWorker.js
Lines 246 to 249 in 3ea2534
Intercepting navigation requests may lead to all sorts of unpredictable behavior and must be avoided alongside static assets interception (like the initial HTML/CSS/JS of the page).
I can also see that what you're doing is navigating to a resource in the next tab. This may prompt the download (depending on the response), but that's not the only way to initiate an in-browser download.
Solution
To control the dow…