Reputation: 67
I have a form action in my Sveltekit backend. I'm trying to return the response from the backend to the front end after I've sent the form and awaited the response from the API
in +page.server.js:
/** @type {import('./$types').Actions} */
export const actions = {
default: async ({ request }) => {
const form = await request.formData();
const apikey = form.get('apikey');
const topic = form.get('topic');
console.log(apikey)
console.log(topic)
async function doPost () {
const res = await fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apikey}`
},
body: JSON.stringify({
'model': 'text-davinci-003',
'prompt': `Tell me something about {topic}`,
'temperature': 0,
'max_tokens': 150
})
})
const json = await res.json()
const result = JSON.stringify(json)
return { success: result };
}
const result = await doPost()
console.log(result)
return { success: result };
}
};
In +page.svelte in the same folder:
<script>
/** @type {import('./$types').PageData} */
export let data;
console.log(data)
</script>
<p>{data}</p>
I only get empty {} back when I try console.log(data) .
Upvotes: 1
Views: 564
Reputation: 184386
data
comes from a load
function, you defined form actions, which is entirely separate and provides a form
property.
(So even if you rename the property, you will get nothing until you send a form post to the endpoint.)
Upvotes: 1