我正在尝试配置SvelteKit以便与我的CMS一起使用。
我在api/query.js
中从我的CMS获取数据,在index.svelte
中从api/query
中获取数据。
它的工作很好,我可以获取到所有数据,但是如果我在fetch请求中包含body,则会出现错误"Cannot read property 'split' of undefined"。 代码:
// 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
}
}
被注释掉的代码部分是导致错误的原因之一。如果我在api/query.js
中使用console.log(req.body)
,它会返回undefined
。
是否有办法使用Express.js的body-parser?还是有其他方法可以解决这个错误?