Discussions

Ask a Question
Back to All

Javascript example call

I want to call API from client JS code, I've tried different ways to do it, and in most of them I receive CORS error, i.e.

    const data = {
      grant_type: 'password',
      username,
      password
    };

    const init = {
      method: 'POST'
      , mode: 'cors'
      , cache: 'no-cache'
      ,  credentials: 'same-origin' // include, *same-origin, omit
      , headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        }
      , redirect: 'follow' // manual, *follow, error
      , referrerPolicy: 'no-referrer' // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      , body: JSON.stringify(data)
    };

    fetch('https://auth.trackunit.com/token', init)
      .then(response => {
        if (response.ok) {
          let resp = response.json();
          debugger;
          console.log(resp);
        }
      })
      .catch(error => {
        debugger;
        console.err(error);
      });

I get the error:

Access to fetch at 'https://auth.trackunit.com/token' from origin 'http://localhost:62108' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Changed mode to 'no-cors', the get error 400 - aborted:

    const data = {
      grant_type: 'password',
      username,
      password
    };

    const init = {
      method: 'POST'
      , mode: 'no-cors'
      , cache: 'no-cache'
      ,  credentials: 'same-origin' // include, *same-origin, omit
      , headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        }
      , redirect: 'follow' // manual, *follow, error
      , referrerPolicy: 'no-referrer' // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      , body: JSON.stringify(data)
    };

    fetch('https://auth.trackunit.com/token', init)
      .then(response => {
        if (response.ok) {
          let resp = response.json();
          debugger;
          console.log(resp);
        }
      })
      .catch(error => {
        debugger;
        console.error(error);
      });

net::ERR_ABORTED 400

Thank you!