Failed to parse URL when using $fetch plugin + proxy
Environment
- Operating System: Darwin
- Node Version: v20.12.2
- Nuxt Version: 3.12.4
- CLI Version: 3.12.0
- Nitro Version: 2.9.7
- Package Manager: [email protected]
- Builder: -
- User Config: modules, app, css, routeRules, runtimeConfig, colorMode, ui, devtools
- Runtime Modules: @nuxt/[email protected], @nuxtjs/[email protected], @nuxt/[email protected], @pinia/[email protected], @samk-dev/[email protected], @nuxt/[email protected], [email protected]
- Build Modules: -
Reproduction
https://stackblitz.com/edit/github-c51gfm-fpwdjf?file=app.vue,plugins%2Fapi.ts
Describe the bug
$fetch plugin with proxy cannot parse URL on server side
Error: [GET] "/api/auth/me": <no response> Failed to parse URL from /api/auth/me
Additional context
No response
Logs
No response
@pi0 Hello! can you look at this bug please, really dont understand why this error happens. i want to proxy request custom $fetch plugin
This is because you're fetching /api/auth/me on the server side, and Node.js's fetch doesn't accept URLs without a host.
You could try this to move this request to the client-side (the same as your login request); the browser will automatically attach the current host to the URL. (Node.js won't do this.)
const { data, error } = useAsyncData(() => {
return fetchUser();
- }
+ }, { server: false });
If you want to use fetchUser on the server side, you'll need to provide the host yourself. For example:
- const { $apiFetcher } = useNuxtApp();
+ const { $apiFetcher, $config } = useNuxtApp();
async function fetchUser() {
try {
console.log('try to fetch user data');
- return $apiFetcher('/auth/me', { method: 'get' });
+ return $apiFetcher(`${$config.proxyUrl}/auth/me`, { method: 'get' });
} catch (e) {
console.log(e);
}
}
const { data, error } = useAsyncData(() => {
return fetchUser();
});