2

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) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("http://localffc.com/rest/V1/directory/areas/AE")
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          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) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    )
  }

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

            </li>
          ))}
        </ul>
      );
    }
  }
}  

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

2

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 "*"
 </Directory>
 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 you have read our privacy policy.

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