0
var ready = function ready(callback) {
      if (document.readyState != "loading") callback();else document.addEventListener("DOMContentLoaded", callback);
    };
    ready(function () {
      "use strict"; 
      var callBstApi = function callBstApi(params) {
        fetch("http://localhost:3000/api/v1/myApi", {
          method: 'POST',
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(params)
        }).then(function (data) {
          console.log(JSON.stringify(params));
        }).catch(function (error) {
          console.log('test is cancelled!');
        });
      };
    });
    

When I call callBstApi(myParams) onload it works but if I call that function from my browser console it shows below error Error!!!

I have to write script in vanilla js.

1
  • 6
    That is because callBstApi is enclosed in the ready function and it is not available to the global scope. If you want to expose it, instead of doing var callBstApi you can do window.callBstApi = .... You can then access the function callBstApi in the window object. Commented Jun 23, 2021 at 7:29

1 Answer 1

1

To further extend on my comment: the reason why callBstApi is not available in your console is because it is not present in the global scope. The function is defined inside your ready function and is therefore inaccessible. To circumvent this, you will want to expose the method to the global window scope. This can be done by doing so:

window.callBstApi = ...

You can now access callBstApi in the global scope (with or without the window. prefix, that is completely optional) and invoke it as such:

callBstApi(myParams);

// If you want to be pedantic, you can do:
window.callBstApi(myParams);

p/s: The only risk is that you'll overwrite whatever that's there, if that key is already found in the window object.

Sign up to request clarification or add additional context in comments.

Comments

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.