Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 132 ยท Data and Async

Axios, HTTP Requests and CORS in React

Use Axios in React - instances, interceptors, loading and error states, cancelling requests with AbortController - compare it with fetch, and finally understand what CORS is and how to fix CORS errors.

React has no built-in way to talk to a server. In Data Fetching you used the browser's fetch. Many codebases use Axios instead, an HTTP client library that wraps the same browser features with a friendlier API. This lesson shows what Axios adds, how to use it correctly inside components (loading, errors, cancellation), and then explains the thing that confuses every beginner at least once: CORS errors.

The editor cannot install npm packages and cannot reach real APIs reliably, so the Axios code is read-only, and the runnable demos use a stand-in with the same shape (an instance, interceptors, cancellation) on top of a fake in-memory server. The stand-in teaches the mechanics; it is not the real Axios.

fetch versus Axios

Both send HTTP requests from the browser. The differences are about convenience.

fetch Axios
Install built in npm install axios
JSON body JSON.stringify and a header yourself pass an object, serialized for you
JSON response await response.json() response.data already parsed
HTTP errors (404, 500) do not reject; check response.ok reject for non-2xx statuses by default
Base URL, shared headers write a wrapper axios.create({ baseURL, headers })
Interceptors write a wrapper built in (request and response)
Timeout AbortSignal.timeout(ms) timeout option
Upload progress not available onUploadProgress

Neither is "better". fetch has no dependency and is enough for many apps; Axios saves boilerplate in apps with many requests, an auth header and consistent error handling. For caching, retries and deduping, a tool such as TanStack Query sits on top of either and is usually the better choice than hand-written useEffect code.

The basics

JSX
// read-only
import axios from 'axios';

// GET with query parameters
const { data } = await axios.get('https://api.example.com/users', { params: { page: 2 } });

// POST with a JSON body
const created = await axios.post('https://api.example.com/users', { name: 'Ada' });
console.log(created.status, created.data); // 201 { id: 7, name: 'Ada' }

// PUT, PATCH, DELETE are the same shape
await axios.delete('https://api.example.com/users/7');

A response object has data (the parsed body), status, statusText, headers and config. If the server answers with a non-2xx status, Axios throws an AxiosError. Its error.response holds the server's reply (when there was one), error.request means the request was sent but nothing came back, and neither means the request could not even be built.

JSX
// read-only
try {
  await axios.get('/api/secret');
} catch (error) {
  if (axios.isAxiosError(error)) {
    if (error.response) console.log('Server said', error.response.status, error.response.data);
    else if (error.request) console.log('No answer: network down, CORS blocked, or timeout');
    else console.log('Setup problem', error.message);
  }
}

Instances and interceptors

Real apps do not write the base URL and the auth header in every call. Create one configured instance and use it everywhere:

JSX
// api.js (read-only)
import axios from 'axios';

export const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 8000,
  headers: { Accept: 'application/json' },
});

// Request interceptor: runs before every request
api.interceptors.request.use((config) => {
  const token = getToken();                       // from memory, not localStorage if you can avoid it
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// Response interceptor: runs for every response or error
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) signOut();  // one place to handle expired sessions
    return Promise.reject(error);
  }
);

Interceptors are the right place for cross-cutting concerns: auth headers, logging, a global "session expired" redirect, mapping errors to a common shape. See Authentication patterns for how this fits a sign-in flow.

A stand-in you can run

The demo below has a fake server (a Map plus a delay), a createClient function that mimics axios.create with interceptors and baseURL, and a React component that loads users with proper loading and error states and a retry button. Failures happen on purpose: the first request to /users fails once.

Stand-in: an Axios-like client with interceptors and a loading/error component

The first attempt ends in the error state, and Retry succeeds. Three habits in the component matter more than any library:

  1. Model three states (loading, error, ready) instead of guessing from data being empty.
  2. Cancel in the cleanup function. The AbortController signal is passed to the request; when the effect re-runs or the component unmounts, abort() stops the old request so its late response cannot overwrite newer data. Axios (since v0.22) accepts signal just like fetch, and it rejects with a cancellation error you should ignore. The older CancelToken API is deprecated.
  3. Do not set state after the request was canceled. The ERR_CANCELED check does that. The older isMounted flags are not needed.

useEffect fetching has more traps (race conditions, caching); read Effect cleanup and Data fetching next to this lesson.

What CORS is

Now the error everyone meets:

Access to XMLHttpRequest at 'https://api.example.com/users' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CORS (Cross-Origin Resource Sharing) is a browser rule, not a server crash and not a bug in React or Axios. It builds on the same-origin policy: JavaScript on one origin may not read responses from a different origin unless that other server agrees. An origin is the combination of scheme, host and port, so http://localhost:5173 and http://localhost:8000 are different origins, and so are http://site.com and https://site.com.

The agreement is made with HTTP headers on the server's response:

HTTP
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true

Things that are important to understand:

  • The request usually reaches the server. The browser sends it, receives the response, and then refuses to hand it to your JavaScript. That is why the server log shows a request and your code shows an error.
  • Only browsers enforce it. curl, Postman and server-to-server calls ignore CORS. "It works in Postman" proves nothing about CORS.
  • The fix is on the server (or a proxy), not in React. No Axios option can override it.

Simple requests and preflight

Some requests are "simple" (a GET or form-style POST with ordinary headers) and are sent directly. Anything else, such as PUT/DELETE, a JSON Content-Type, or an Authorization header, triggers a preflight: the browser first sends an OPTIONS request asking "would you allow this?" and only sends the real request if the answer's Access-Control-Allow-* headers say yes. A frequent cause of confusing errors is a server that handles GET correctly but returns an error for the OPTIONS request.

Simulation: how the browser decides about CORS

Try "Allows any origin (*)" together with "Send cookies": the browser still blocks it. With credentials the server must name your exact origin and also send Access-Control-Allow-Credentials: true; on the client side you opt in with withCredentials: true in Axios or credentials: 'include' in fetch.

How to fix a CORS error

Pick the fix that matches who controls the server.

  1. You control the API: add CORS headers. In Express use the cors middleware, in Laravel the config/cors.php file, in Django django-cors-headers. Allow only the origins you need rather than * for anything with logins.
  2. You do not control the API, during development: use your dev server's proxy, so the browser talks to its own origin and the dev server forwards the call (server to server, no CORS). With Vite:
JavaScript
// vite.config.js (read-only)
export default {
  server: {
    proxy: { '/api': { target: 'https://api.example.com', changeOrigin: true } },
  },
};

Then call axios.get('/api/users') from React. In production, a reverse proxy (nginx, a CDN rule or your backend) does the same job. 3. You do not control the API, in production: call it from your own server (a backend route or a server function) and let React call that. Never use a public "CORS proxy" for private data: it can read everything that passes through. 4. Do not "fix" it by disabling browser security, by installing extensions that strip headers, or by mode: 'no-cors' in fetch. That mode gives you an opaque response that JavaScript cannot read, so it only hides the error.

Common mistakes

  • Blaming Axios or React for a CORS error. Check the response headers in the browser's Network tab instead.
  • Forgetting that OPTIONS must succeed for preflighted requests, including through authentication middleware that rejects it.
  • Using * together with cookies, which browsers refuse.
  • Storing tokens in localStorage and attaching them in an interceptor without thinking about XSS; see React security.
  • Not cancelling requests in effects, so a slow old response overwrites a newer one.
  • Hard-coding the base URL in components rather than using one instance with baseURL from an environment variable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about Axios and fetch is correct?

    fetch resolves for any HTTP response and you check response.ok yourself. Axios throws an AxiosError for statuses outside 2xx.
  2. 2. What is an Axios interceptor typically used for?

    Interceptors centralize cross-cutting concerns such as authorization headers, logging and global error handling.
  3. 3. Why should an effect that fetches data abort the request in its cleanup?

    Aborting ties the request to the effect's lifetime and prevents race conditions between old and new requests.
  4. 4. Where is a CORS error actually fixed?

    CORS is enforced by the browser based on the server's headers. Only the server, or a proxy that talks to it, can grant permission.
  5. 5. Why does a request that works in Postman fail with a CORS error in the browser?

    CORS protects users of browsers. Tools like Postman and curl are not bound by it.

Summary

  • Axios wraps HTTP with parsed JSON, baseURL, shared headers, interceptors and rejection on non-2xx; fetch needs a little more code but no dependency.
  • Create one Axios instance, put auth and error handling in interceptors, and cancel requests with AbortController in effect cleanups.
  • Track loading, error and ready explicitly, and give the user a retry.
  • CORS is a browser safeguard: the server must send Access-Control-Allow-Origin (and friends), and preflight OPTIONS requests must succeed.
  • Fix CORS on the server or with a proxy, never by disabling security or using no-cors.

Next: Async Patterns