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>
3
  • 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. Commented Dec 3, 2022 at 8:17
  • 2
    Setting no-cors mode is not a solution to your actual issue, see stackoverflow.com/questions/43871637/… Commented Dec 3, 2022 at 8: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.' Commented Dec 3, 2022 at 8:25

1 Answer 1

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)
  });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! I get this now in console: {type: 'opaque', url: '', redirected: false, status: 0, ok: false, …}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.