【发布时间】:2021-05-16 17:21:30
【问题描述】:
我正在尝试设置 SvelteKit 以将其与我的 CMS 一起使用。
我正在从 api/query.js 中的 CMS 获取数据,并从 index.svelte 中的 api/query 获取数据。
效果很好,我可以获取全部数据,但如果我在获取请求中包含正文,我会收到错误“无法读取未定义的属性‘拆分’”。代码:
// 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 正文解析器?或者有没有其他方法可以解决这个错误?
【问题讨论】: