Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix CORS error on 3rd party API call in Nuxt 3?

I am working on Nuxt 3 with useFetch hook to call API. When I call the 3rd party API post https://apitest.bankfeeds.com.au/v1/customer/data using useFetch hook, it returns the CORS error

CORS Missing Allow Origin

I have the ssr: false in my nuxt.config.ts file

check error here

I have tried to set cors on nuxt config file but not working and returns the same error.

like image 749
Kishan Bhensadadiya Avatar asked Oct 11 '25 11:10

Kishan Bhensadadiya


2 Answers

It's probably giving you a CORS error because you are fetching the API through the browser and not trough the backend.

Most third party API's deny cross-origin requests.

Try fetching the API from postman, if it works just put the fetch call in the server-side backend.

like image 78
chillin.killer Avatar answered Oct 14 '25 12:10

chillin.killer


Use server/api folder to avoid such problems. This way you don't have to lose the benefits of useFetch composable. Make your requests server-to-server via Nitro.

api/server/auth.post.js

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const runtimeConfig = useRuntimeConfig();

  try {
    await $fetch(`${runtimeConfig.public.apiBase}/login`, {
      method: "POST",
      body: { username: body.username, password: body.password },
      headers: { "Content-Type": "application/json" },
    });
  } catch (err) {
    throw createError({
      message: "Authorization Failed",
      statusCode: 401,
    });
  }

  return {
    message: "success",
  };
});
like image 37
Orhan Bayram Avatar answered Oct 14 '25 13:10

Orhan Bayram