0
export const executeCode = (data) => {
       return fetch("https://ide.geeksforgeeks.org/main.php",{
              method: "POST",
              headers: {
                     Accept : "application/json",
                     "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
              },
              body: data
       })
       .then(response => response.json())
       .catch(err => console.log(err))
}

I'm sending a POST request to G4G's compiler API. It's working fine in postman but not working in my react app.

Error msg (image)

working in postman (image)

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
Het Delwadiya
  • 83
  • 1
  • 10
  • Yes, i tried but no luck – Het Delwadiya Feb 04 '22 at 07:09
  • You need to specify below HTTP headers in your backend code whatever language are u used. Access-Control-Allow-Origin – Name of the domain allowed for cross domain requests. * indicates all domains are allowed. Access-Control-Allow-Methods – List of HTTP methods can be used during request. Access-Control-Allow-Headers – List of HTTP headers can be used during request. – Jayesh Naghera Feb 04 '22 at 07:12
  • one more question react & php both are in HTTPS url? – Jayesh Naghera Feb 04 '22 at 07:14
  • @JayeshNaghera I can't change G4G's backend. Access-Control-Allow-Methods accepting GET & POST, and for Access-Control-Allow-Origin I was thinking that it's *. because its working in postman. And my website is in localhost and G4G's backend is in https. – Het Delwadiya Feb 04 '22 at 07:20
  • server & client both should be same http or https check if not, refer https://stackoverflow.com/a/4032123/6341267 – Jayesh Naghera Feb 04 '22 at 07:26

3 Answers3

1

When making a call from an website there are security considerations to be taken into account. One of them is CORS.

In a nut shell the browser asks the server if it allows HTTP calls (calls that are considered not simple actually).

Postman works because it doesn't do this check.

G4G need to respond to OPTIONS requests with a proper CORS response that allows your host to call them.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
1

Please add to the header of the request Access-Control-Allow-Origin: * let me know if it's working

mmantach
  • 148
  • 10
1

Add this line of code on backend in .htacess file

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "POST,GET,OPTIONS,DELETE,PUT"
Header set Access-Control-Allow-Headers "*"
</IfModule>
Mateen Kiani
  • 2,869
  • 2
  • 19
  • 29
kashan ilyas
  • 155
  • 1
  • 1
  • 10