I have been looking for a possible fix for this as I have no clue why this is happening.
I have a really basic login POST function inside the /api
folder.
/src/routes/api/login/+server.ts
import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
export const POST: RequestHandler = ({ cookies }) => {
const data = await request.json();
...
return json({ employee: { email: data.email, id: 123 }});
};
The problem is that when I do POST http://localhost:5173/api/login
it returns a 405 error: GET method not allowed
.
If I move the /login
folder outside the /api
folder, and try again the request POST http://localhost:5173/login
(this time without /api) it works fine.
The request is made from the /auth/+page.svelte file, but I’ve tried it in Postman and the result is the same.
/src/routes/auth/+page.svelte
<script lang="ts">
import { goto } from '$app/navigation';
let email = '';
let password = '';
const login = async () => {
const response = await (
await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
headers: {
'content-type': 'application/json'
}
})
).json();
if (response.employee) {
goto('/');
} else {
// Error
loading = false;
}
};
</script>
...
Maybe I’ve missed a configuration…? I have been working with SvelteKit for several months now and this has never ocurred before. I have also not seen any issue or discussion threads related to this, which lead me to believe it is a problem on my end, but have yet to find anything that I could be doing wrong or that could fix this.
Would very much appreciate some suggestions/ideas/fixes and thanks in advance!
2
Answers
I've just discovered that the error was totally my bad. I was intercepting the request in the hooks.server.ts file and the request made to
/api/auth
was redirecting to/login
.As
locals.employee
didn't exist the request was not displaying the/api/auth
route, but the/login
route.Can you try this one?