I am trying to get this fetch method to work in Svelte
When the page.svelte calls the function to fetch the data, in the console I receive this
[HTTP/1.1 405 Method Not Allowed 19ms]
Which I have narrowed down to this
POST method not allowed
Is there a variable I need to set in the config files or is there another solution which I am missing?
// svelte.config.js
import adapter from '@sveltejs/adapter-auto';
const config = {
kit: {
adapter: adapter(),
methodOverride: {
allowed: ['POST']
},
}
};
export default config;
Both files are in the Routes folder
// fetch-data.js
export const POST = async(data) => {
const response = // get data function here
return {
body: {
data: response
}
}
}
// page.svelte
async function fetchData() {
const response = await fetch('./fetch-data', {
method: 'POST',
body: JSON.stringify(),
headers: {
'content-type': 'application/json'
}
})
const { data } = await response.json()
return data
}
I am trying to get this fetch method to work in Svelte
When the page.svelte calls the function to fetch the data, in the console I receive this
[HTTP/1.1 405 Method Not Allowed 19ms]
Which I have narrowed down to this
POST method not allowed
Is there a variable I need to set in the config files or is there another solution which I am missing?
// svelte.config.js
import adapter from '@sveltejs/adapter-auto';
const config = {
kit: {
adapter: adapter(),
methodOverride: {
allowed: ['POST']
},
}
};
export default config;
Both files are in the Routes folder
// fetch-data.js
export const POST = async(data) => {
const response = // get data function here
return {
body: {
data: response
}
}
}
// page.svelte
async function fetchData() {
const response = await fetch('./fetch-data', {
method: 'POST',
body: JSON.stringify(),
headers: {
'content-type': 'application/json'
}
})
const { data } = await response.json()
return data
}
Share
Improve this question
asked Jul 24, 2022 at 12:00
MCCMCC
5422 gold badges5 silver badges23 bronze badges
3 Answers
Reset to default 4I had the same error for a different reason, and the syntax in your question and answer has changed again so I'll add my discoveries:
+page.server.ts
should no longerexport const POST
but insteadexport const actions: Actions = { ... }
which don't need to return anything.+server.ts
still usesfunction POST(event: RequestEvent)
and needs to return aResponse
(from the Fetch API).- Cookies can no longer be set with
setHeaders
but must usecookies
instead. Otherwise the handler also returns 405.
The solution was to change the POST
variable name to lowercase in the get-data.js file
I had the same problem because of old SvelteKit version (I used .456, current version at the time this was written is .484). So make sure you have the most recent version of framework, when referring to the docs ;)