I am creating 1 application in react and have a requirement to call magento api from react js

My magento application is hosted on http://localserver.com and react is with http://localhost:3000/

Below is my code in react

import React, { Component } from 'react';  
class App extends Component{

  constructor(props) {
    this.state = {
      error: null,
      isLoaded: false,
      items: []

  componentDidMount() {
    .then(res => res.json())
      (result) => {
          isLoaded: true,
          items: result
      // Note: it's important to handle errors here
      // instead of a catch() block so that we don't swallow
      // exceptions from actual bugs in components.
      (error) => {
          isLoaded: true,

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
          {items.map(item => (
            <li key={item.name}>


export default App; 

But I am getting below error

Access to fetch at 'http://localserver.com/rest/V1/directory/areas/AE' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Please help me how i can fix it.

1 Answer 1


I go the solution

Go to your site config file for example

nano /etc/apache2/sites-available/localmagento.com.conf

and add

Header set Access-Control-Allow-Origin "*"

as below

<VirtualHost *:80>
 ServerAdmin [email protected]
 DocumentRoot /var/www/html/magento2/
 ServerName localmagento.com
 ServerAlias www.localmagento.com
 <Directory /var/www/html/magento2/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    Header set Access-Control-Allow-Origin "*"
 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined

and use a2enmod headers and then restart server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.