1

I am trying to write a javascript and execute it in a Html file. I can run the Javascript file on my own computer without problems, but when I add it in a Html file and run it in a browser I got an Cors Error. I added the mode: 'no-cors'. After that, I got a 'SyntaxError: Unexpected end of input'. I can still only run the Javascript part so I am completely lost in trying to find the syntaxerror. Does anyone have a clue?

<html>
  <body>
<script>

var apiUrl = 'https://bulkfollows.com/api/v2';

// define the data to be sent to the API
var data = {
  key: "key",
  action: "balance"
};

fetch(apiUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  mode: 'no-cors',
  body: JSON.stringify(data)
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.log("Error: " + error));

</script>
</body>
</html>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 1
    The dev tools provide a **Network** tab. Is the resource _found_ (e.g. HTTP 200 response)? Inspect the response that you’re getting from the API. It’s very likely an empty string. – Sebastian Simon Dec 03 '22 at 08:17
  • 2
    Setting `no-cors` mode is not a solution to your actual issue, see https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – Teemu Dec 03 '22 at 08:24
  • 1
    Yes I get a 200, and I cannot see the answer in the Network tab, because it says 'No data found for resource with given header.' – Markus Handel Dec 03 '22 at 08:25

1 Answers1

1

Try this. your error will be solved. but for cors, setting cors will not solve your problem . check comment

 fetch(apiUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  mode: "no-cors",
  body: JSON.stringify(data)
})
  .then((response) => {
        if (!response.ok) {
            throw response; 
        }
        return response.json();
    })
  .then((data) => console.log(data))
  .catch(function(error) {
        console.log( error)
  });
Atik Hashmee
  • 393
  • 3
  • 12