Search code examples
javascriptasync-awaitxampp

CORS error with JS async/await but not when I paste the URL directly into browser


When I put the URL http://192.168.1.136:8080/epost_backend/api.php?method=getCategories into chrome it returns the output from the API that I have built.

Image of output But when I put the exact same URL into a javascript async/await function, it always gets trapped in the catch error...

Result from async/await function

Here is network tab showing CORS error: ERRORS FROM DEV TOOLS

Here is the HTML/JS file:

<!doctype html> 
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<script>
  async function getCategories(){
    try{
      const res = await fetch("http://192.168.1.136:8080/epost_backend/api.php?method=getCategories")
      const output = await res.json()
      document.getElementById('result').innerHTML = output
    }
    catch{
      document.getElementById('result').innerHTML = "THERE WAS AN ERROR"
    }
  }
</script>
<body onLoad='getCategories()'>
  <h1>RESULT</h1>
  <div id='result'></div>
</body>
</html>

Any thoughts on what I am doing wrong or why I cant get this info this way??

I will be monitoring and answering any questions....

Thanks so much!


Solution

  • You simply need to enable CORS on your PHP server. You do this by setting a number of headers. At a minimum set Access-Control-Allow-Origin "*" to allow all origins to make requests to your PHP server.

    A good reference can be found at this site: https://enable-cors.org/server_php.html