h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Failed to parse URL when using $fetch plugin + proxy

Open lammerfalcon opened this issue 1 year ago • 1 comments

Environment



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

lammerfalcon avatar Jul 20 '24 11:07 lammerfalcon

@pi0 Hello! can you look at this bug please, really dont understand why this error happens. i want to proxy request custom $fetch plugin

lammerfalcon avatar Jul 22 '24 15:07 lammerfalcon

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();
});

kricsleo avatar Apr 22 '25 08:04 kricsleo