Skip to main content

Fixing CORS Issue When Calling API in React Native

· 2 min read
Đặng Anh Sơn
Happy developer

Fixing CORS Issue When Calling API

Introduction:

Many developers face issues related to CORS. But what is CORS? CORS is a mechanism that allows various resources (JavaScript) on a web page to be requested from a domain different from the domain of that page. This is the CORS policy error that most developers encounter. When calling an API to a server without the Access-Control-Allow-Origin header or with an invalid value, this error occurs, and data cannot be retrieved from the API.

image.png

Installing rn-fetch-blob to Address the Issue

  • First, we need to install the rn-fetch-blob library. If using npm:
npm install --save rn-fetch-blob

using yarn

yarn add rn-fetch-blob
  • To use it on IOS, add the following to the Podfile:
pod 'rn-fetch-blob',
:path => '../node_modules/rn-fetch-blob'
  • How it works: image.png

  • Example of usage:

import RNFetchBlob from 'rn-fetch-blob';

export async function apiLogin({
phone,
password,
}: {
phone: number | string;
password: string;
}): Promise<any> {
return RNFetchBlob.config({
trusty: true,
}).fetch(
'POST',
`${URl_API}/api/auth/login?phone=${phone}&password=${password}`,
);
}

Now your API calls will work. In the example, I'm demonstrating an API login with parameters phone and password. The use of trusty: true in RNFetchBlob.config helps us resolve this issue.

Other Ways to Handle CORS Errors

A common misconception, especially for developers working with APIs from large companies with comprehensive documentation, is thinking that CORS is a frontend task. But in reality, CORS is entirely a backend task.

You can communicate with the backend to handle CORS.

You can change the project's port to match.

Both approaches are effective, but for standardization, it's best to consult the backend for the most accurate handling.

Conclusion

Using rn-fetch-blob is straightforward and easy, although it may not be the most optimal solution. Still, it can be a choice for you in cases where you face challenges, and the project needs to progress quickly without relying heavily on the backend.

I hope this article is helpful to you. Thank you for reading!

If you have any questions or comments, please leave them below. We can discuss this topic together.