i have a frontend where I define a string in this case videoLink
.
Besides that I have an async function that starts when a button is clicked.
//sveltekit
async function addToQueue(){
console.log(videoLink);
const res = await fetch('/tool/server', {
method: 'POST',
body: {
videoData: videoLink
}
})
const json = await res.json()
console.log(json);
videoLink = "";
}
This function sends an http-post request with fetch to my server.js file.
/** @type {import('@sveltejs/kit').RequestHandler} */
export async function POST(event) {
const data = await event.request.body;
const link = data.videoData;
console.log(link)
}
when i run the post-request (by clicking the Button in my frontend), my server logs undefined
. As far as I know the server gets the POST request, because it logs only if I click the button.
But why does it return undefined
? I have tried to parse the json, but it didn't work. Can anyone help me? What is wrong with my JSON?
CodePudding user response:
Open the developer tools in your browser. Look at the Network tab. Examine the Request payload you are sending:
[object Object]
fetch
doesn't support plain objects for the body
option. It will convert them to strings with their toString()
method.
You need to either provide:
- an object which
fetch
does support. The common options are- URLSearchParams for
application/x-www-form-urlencoded
data - FormData for
multipart/form-data
- URLSearchParams for
- an encoded string (such as the output of
JSON.stringify
) and also set thecontent-type
HTTP request header to match
Which you choose will depend on what encodings the server side code supports.
CodePudding user response:
So I have provided
headers: {
'Content-Type': 'application/json'
}
to fetch the data.
On the server side I've done the following:
export async function POST({request}) {
const data = await request.json()
console.log(data)
return {}
}
Now the function returns {}
, which isn't mandatory. The reason it works now is that POST gets {request}
as an argument.
Notice the curly braces. Thanks a lot to @Quentin for his help.