【问题标题】:SvelteKit req.body undefinedSvelteKit req.body 未定义
【发布时间】: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.jsconsole.log(req.body) 它返回undefined

有没有办法可以使用 Express.js 正文解析器?或者有没有其他方法可以解决这个错误?

【问题讨论】:

    标签: svelte sveltekit


    【解决方案1】:

    为两条路由设置content-type 标头。

    还要确保所有标题键都是小写的。

    例子:

    ...
        headers: {
            'authorization': `Basic ${auth}`,
            'content-type': 'application/json'
        },
    ...
    

    【讨论】:

    • 谢谢!我一直在尝试使用 hooks.ts 和 StreamReaders 中的中间件解析 request.body 一个小时,但这使得使用 request.body 并完成它成为可能。
    猜你喜欢
    • 2012-02-28
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多