Reputation: 69
I'm trying to set up SvelteKit to use it with my CMS.
I'm fetching data from my CMS in api/query.js
, and fetching data from api/query
in index.svelte
.
It works great and I can get the whole data, but I get an error "Cannot read property 'split' of undefined" if I include body in the fetch request. Code:
// api/query.js
export async function post(req) {
const url = API_URL;
const auth = Buffer.from(`${API_USER_EMAIL}:${API_USER_PASSWORD}`).toString('base64');
const res = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Basic ${auth}`,
},
body: JSON.stringify(req.body),
});
const data = await res.json();
return {
status: data.code,
body: data
}
}
// index.svelte
export async function load({ fetch }) {
const res = await fetch('/api/query', {
method: 'POST',
// body: JSON.stringify({
// query: 'site.title',
// }),
});
const data = await res.json();
return {
status: data.status || 200,
props: data
}
}
The commented out portion of code is one that's causing an error. If I console.log(req.body)
in api/query.js
it returns undefined
.
Is there a way I could use Express.js body-parser? Or is there any other way to resolve this error?
Upvotes: 3
Views: 1913
Reputation: 679
Set the content-type
header for both routes.
Also make sure all header keys are in lowercase.
Example:
...
headers: {
'authorization': `Basic ${auth}`,
'content-type': 'application/json'
},
...
Upvotes: 1