Open2
Nuxt でサーバー側でクッキーを付与する `useRequestFetch()` は $fetch を置き換えていると機能しないので注意が必要
Nuxt で useFetch を使用すると、サーバー側で動作する際は $fetch ではなく useRequestFetch が使用されます。これにより、サーバー側の fetch でもクッキーを付与する処理が行われています。
(useAsyncData の場合は行われないので注意)
しかしこのページのような対応を行っていると、その入れ替えを行ってくれません。
もしこの対応を onRequestError
などの共通処理のために採用している場合は、
onRequestError
は配列を設定することができますので、それをもとにした対応 = $api を使用しない対応に、変更することで対処可能です。
コード例
const mergeOnErrors = <T>(
options: UseFetchOptions<T>,
): {
onRequestError: OnErrorType<'onRequestError'>
onResponseError: OnErrorType<'onResponseError'>
} => {
// マージしたい onRequestError
const logOnRequestError = ({ request, error }: OnErrorContext<'onRequestError'>) => {
if (import.meta.dev) {
console.error('API: onRequestError', request, error.message)
} else if (import.meta.client) {
// Sentry に送信
}
}
// マージしたい onResponseError
const logOnResponseError = ({ response }: OnErrorContext<'onResponseError'>) => {
if (import.meta.dev) {
console.error('API: onResponseError', response)
} else if (import.meta.client) {
// Sentry に送信
}
}
const onRequestError = Array.isArray(options.onRequestError)
? options.onRequestError.concat(logOnRequestError)
: options.onRequestError
? [options.onRequestError, logOnRequestError]
: logOnRequestError
const onResponseError = Array.isArray(options.onResponseError)
? options.onResponseError.concat(logOnResponseError)
: options.onResponseError
? [options.onResponseError, logOnResponseError]
: logOnResponseError
return {
onRequestError,
onResponseError,
}
}
export const useApiFetch: typeof useFetch = <T>(
url: Ref<ReqT> | ReqT | (() => ReqT),
options: UseFetchOptions<T> = {},
) => {
const { onRequestError, onResponseError } = mergeOnErrors(options)
return useFetch(url, {
...options,
onRequestError,
onResponseError,
})
}