5

We are developing a headless eCommerce application for our company, so here is my question how to access the magento2 product collection graphql API which is running on a server using react js which is running on localhost:3000, I don't understand why it is blocking the request and please explain this one or refer any reference to get understand this and I am attaching the console error which I got while connecting

enter image description here

index.js

const link = createHttpLink({
  uri: 'http://192.168.1.16/graphql',
  headers: {
    "Access-Control-Allow-Origin": "http://192.168.1.69:3000",
    "Access-Control-Allow-Methods": "GET, POST, PUT",
    "Access-Control-Allow-Headers": "Content-Type"
  },
  mode: 'no-cors',
});


const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

1 Answer 1

4

We also faced the same issue for my Headless project.

Try below two possible solutions.

Solution 1 :

Add the below line at the top of the index.php file. You can find the index.php file in the root path Or inside of pub folder in Magento.

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");

The index file screenshot with the above code is as below. enter image description here

Solution 2 :

Install & Configure below CORS Magento 2 module. This module allows you to enable Cross-Origin Resource Sharing (CORS) REST API requests in Magento 2 by adding the appropriate HTTP headers and handling the pre-flight OPTIONS requests.

Magento 2 CORS Module

4
  • Thanks for your answer, it wasn't worked for me but add two more lines it worked for me. Jan 23 at 7:01
  • 1
    @Naveen Raj Kumar I have incorporated your suggestion in my answer. Now it will help others to resolve this issue!!! Jan 23 at 7:11
  • 1
    Thank you so much, Solution 1 helped me so much with headless Nuxt 3 and Magento 2.4. Once added this to the /pub/index.php and rebooted my system then the data came through without cors issues.
    – Sebastian
    Jun 12 at 1:34
  • @Sebastian Solution 1 worked for you. I am happy to hear that. Jun 12 at 5:58

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.