Provide correct MIME type for dynamic endpoint routes in dev (#4356)

This commit is contained in:
Chris Swithinbank 2022-08-17 20:07:14 +02:00 committed by GitHub
parent 500332a426
commit beed20be4a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 51 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Provide correct MIME type for dynamic endpoint routes in dev

View file

@ -345,7 +345,11 @@ async function handleRequest(
await writeWebResponse(res, result.response);
} else {
let contentType = 'text/plain';
const computedMimeType = route.pathname ? mime.getType(route.pathname) : null;
// Dynamic routes dont include `route.pathname`, so synthesise a path for these (e.g. 'src/pages/[slug].svg')
const filepath =
route.pathname ||
route.segments.map((segment) => segment.map((p) => p.content).join('')).join('/');
const computedMimeType = mime.getType(filepath);
if (computedMimeType) {
contentType = computedMimeType;
}

View file

@ -246,6 +246,26 @@ describe('Development Routing', () => {
expect(body.slug).to.equal('thing4');
expect(body.title).to.equal('data [slug]');
});
it('correct MIME type when loading /home.json (static route)', async () => {
const response = await fixture.fetch('/home.json');
expect(response.headers.get('content-type')).to.match(/application\/json/);
});
it('correct MIME type when loading /thing1.json (dynamic route)', async () => {
const response = await fixture.fetch('/thing1.json');
expect(response.headers.get('content-type')).to.match(/application\/json/);
});
it('correct MIME type when loading /images/static.svg (static image)', async () => {
const response = await fixture.fetch('/images/static.svg');
expect(response.headers.get('content-type')).to.match(/image\/svg\+xml/);
});
it('correct MIME type when loading /images/1.svg (dynamic image)', async () => {
const response = await fixture.fetch('/images/1.svg');
expect(response.headers.get('content-type')).to.match(/image\/svg\+xml/);
});
});
describe('file format routing', () => {

View file

@ -0,0 +1,14 @@
export async function getStaticPaths() {
return [
{ params: { image: 1 } },
{ params: { image: 2 } },
];
}
export async function get({ params }) {
return {
body: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200">
<title>${params.image}</title>
</svg>`
};
}

View file

@ -0,0 +1,7 @@
export async function get() {
return {
body: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 200">
<title>Static SVG</title>
</svg>`
};
}