harshal
harshal

Reputation: 10863

How to pass username and password credentials while fetching data from api in javascript?

I am using flowroute api and need to fetch data but not sure how to add authentication credentials i.e can be seen when I pass the query url in the browser How can I pass it in the javascript. I am using wix platform and adding javascript code as given below

// For full API documentation, including code examples, visit http://wix.to/94BuAAs
import {fetch} from 'wix-fetch';
$w.onReady(function () {
    fetch('https://api.flowroute.com/v2/numbers/available?starts_with=800&limit=3?',{method: 'get',auth:{user:'28288282', pass:'099299292991'}})
      .then( (httpResponse) => {
       console.log(httpResponse.ok);
    if (httpResponse.ok) {

      return httpResponse.json();
    } else {
      return Promise.reject("Fetch did not succeed");



  }
  } )
  .then(json => console.log(json))
  .catch(err => console.log(err));

    //TODO: write your page related code here...



});

what is the correct method to pass username and password to the API so I can get a json response instead of current 401 Unauthorized response status

https://api.flowroute.com/v2/numbers/available?starts_with=800&limit=3 enter image description here

Updating my Answer to show you the Network Call Details Request & Response headers ae as given bwlow in the screenshot enter image description here enter image description here

enter image description here

Upvotes: 4

Views: 14368

Answers (1)

agarwalankur85
agarwalankur85

Reputation: 274

Try:

fetch('https://api.flowroute.com/v2/numbers/available?starts_with=800&limit=3?', {
  method: 'get',
  headers: {
    "Content-Type": "text/plain",
    'Authorization': 'Basic ' + btoa(username + ":" + password),
  },
})

Upvotes: 6

Related Questions