处理 nuxt3 usefetch 上的错误

5 vue.js nuxt.js vuejs3 nuxtjs3

我只是不知道如何处理这里的错误:

const { error, data } = useFetch('https://example.app/api/contact', {
   method: "POST",
   headers: { "Content-Type": "application/json" },
   body: {
      name: form.name.value,
      email: form.email.value,
      message: form.message.value
   }
});
console.log(error.value, error)
Run Code Online (Sandbox Code Playgroud)

对于错误本身,它返回带有 _error 的 ref ,其中包含有错误的对象。但无论如何我无法得到这些错误..

Abo*_*ang 9

参考: https: //v3.nuxtjs.org/api/composables/use-fetch \nuseFetch 返回值 {data,ending,error,refresh},这是一个示例。

\n

\r\n
\r\n
const { data, pending, error, refresh } = await useFetch(\n  \'https://api.nuxtjs.dev/mountains\',\n  {\n    pick: [\'title\']\n  }\n)
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

BTW\xef\xbc\x8cuseFetch 返回一个Promise,在您的示例中,您可以执行以下操作。

\n

\r\n
\r\n
useFetch(\'https://example.app/api/contact\', {\n  method: "POST",\n  headers: {\n    "Content-Type": "application/json"\n  },\n  body: {\n    name: form.name.value,\n    email: form.email.value,\n    message: form.message.value\n  }\n}).then(res => {\n  const data = res.data.value\n  const error = res.error.value\n  if (error) {\n    // dealing error\n    console.log(error)\n  } else {\n    console.log(data)\n  }\n}, error => {\n  console.log(\'exception...\')\n  console.log(error)\n})
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n