最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAX Jquery Call returning 401 (unauthorized) - API Call - Stack Overflow

programmeradmin1浏览0评论

So I'm creating a GET request to this API: /.

A sample URL to test in your browser is:

The username is "admin" and password is "password".

Running the sample URL in the browser gives me a popup asking for the authentication and upon entering it correctly, I get back a JSON response text.

However, when I run this on code, it doesn't work. I've scoured the web for answers and each solution doesn't work. I've tried admin:password@url, passing in the username and password as data parameters in the GET request, and even using the BTOA hash thing to pass that to the web server. Alas to no results. I've attached my code I'm using right now - hope some good soul can help me out of this problem.

My error (EDIT 1):

---------CODE--------------

render() {
    var url = this.props.url;
    var zip = '94305';
    // var zip = this.props.zip;
    // create the prop type later with built in functionality
    var query = zip + this.props.query;
    var username = "admin";
    var password = "password";
    var ret_data = textbookApi(url, query, username, password);
    console.log("after");

    // if data is null, ignore
    // else
    // this.setState({textbooks: ret_data});

    return (
      <div>

      </div>
    );
  }

}

export default Search;

function makeBaseAuth(user, pswd) { 
  var token = user + ':' + pswd;
  var hash = "";
  if (btoa) {
    hash = btoa(token);
  }
  return "Basic " + hash;
}

function textbookApi(url_link, query, username, password) {
  // console.log("INSIDE");
  console.log(makeBaseAuth(username, password));
  $.ajax({
    type: "GET",
    url: url_link,
    data: {
      'search' : query
    },
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', makeBaseAuth(username, password));
    },
    success: function(data) {
      console.log("WORKS!!!!!!!!!!!!!!!!!!!!!!!!!");
      console.log(data);
      return data;
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(url_link, status, err.toString());
    }.bind(this)
  });
}

So I'm creating a GET request to this API: https://immense-depths-6983.herokuapp./search/.

A sample URL to test in your browser is: https://immense-depths-6983.herokuapp./search?search=94305

The username is "admin" and password is "password".

Running the sample URL in the browser gives me a popup asking for the authentication and upon entering it correctly, I get back a JSON response text.

However, when I run this on code, it doesn't work. I've scoured the web for answers and each solution doesn't work. I've tried admin:password@url, passing in the username and password as data parameters in the GET request, and even using the BTOA hash thing to pass that to the web server. Alas to no results. I've attached my code I'm using right now - hope some good soul can help me out of this problem.

My error (EDIT 1):

---------CODE--------------

render() {
    var url = this.props.url;
    var zip = '94305';
    // var zip = this.props.zip;
    // create the prop type later with built in functionality
    var query = zip + this.props.query;
    var username = "admin";
    var password = "password";
    var ret_data = textbookApi(url, query, username, password);
    console.log("after");

    // if data is null, ignore
    // else
    // this.setState({textbooks: ret_data});

    return (
      <div>

      </div>
    );
  }

}

export default Search;

function makeBaseAuth(user, pswd) { 
  var token = user + ':' + pswd;
  var hash = "";
  if (btoa) {
    hash = btoa(token);
  }
  return "Basic " + hash;
}

function textbookApi(url_link, query, username, password) {
  // console.log("INSIDE");
  console.log(makeBaseAuth(username, password));
  $.ajax({
    type: "GET",
    url: url_link,
    data: {
      'search' : query
    },
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', makeBaseAuth(username, password));
    },
    success: function(data) {
      console.log("WORKS!!!!!!!!!!!!!!!!!!!!!!!!!");
      console.log(data);
      return data;
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(url_link, status, err.toString());
    }.bind(this)
  });
}
Share Improve this question edited Dec 7, 2016 at 17:33 AceGravity asked Dec 7, 2016 at 6:56 AceGravityAceGravity 3433 gold badges6 silver badges13 bronze badges 4
  • What's the error? – curv Commented Dec 7, 2016 at 6:59
  • Also your Ajax call should go into the ponentDidMount method if possible – curv Commented Dec 7, 2016 at 7:00
  • i think he has a CORS problem – madalinivascu Commented Dec 7, 2016 at 7:02
  • @zinc, I just changed it to there. Pardon my questions as a beginner, why should I place Ajax calls in ponentDidMount? – AceGravity Commented Dec 7, 2016 at 17:35
Add a ment  | 

3 Answers 3

Reset to default 1

Try to send your http header with username and password as Basic Authentication method

I tried this method on Jquery ajax call

var settings = {
      "async": true,
      "crossDomain": true,
      "url": "https://immense-depths-6983.herokuapp./search?search=94305",
      "method": "GET",
      "headers": {
        "authorization": "Basic YWRtaW46cGFzc3dvcmQ=",
        "cache-control": "no-cache",
        "postman-token": "54733c33-4918-811b-3987-69d6edeaa3a0"
      }
    }

$.ajax(settings).done(function (response) {
  console.log(response);
});
  1. Make sure you enabled cross domain access form your server side.... & not getting any error related to that.
  2. Pass the username & password as basic authentication in ajax http method.

    It worked for me Output :

-[ -{ "id" : 0, "title" : Basic Electronics: An Introduction to Electronics for Science Students, "author" : Curtis Meyer, "no" : 0, "class" : , "isbn" : 5800066848142 }, -{ "id" : 0, "title" : Programming Abstractions in C++, "author" : Jerry Cain, "no" : 0, "class" : CS 106B CS 106X, "isbn" : 1 }, -{ "id" : 0, "title" : The Mind's Machine: Foundations of Brain and Behavior, "author" : Neil Verne Watson, "no" : 0, "class" : Think, "isbn" : 9780878939336 }, -{ "id" : 0, "title" : Physics for Scientists and Engineers: A Strategic Approach, "author" : Randall D. Knight, "no" : 0, "class" : Physics 41, "isbn" : 9780321752918 },.... .... ...

Try https://www.base64decode to encode & decode

To make an AJAX request using CORS, the server needs to be configured to accept cross-origin requests, otherwise ajax call will fail. Read these article to know more about it:

https://zinoui./blog/cross-domain-ajax-request

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

How to get a cross-origin resource sharing (CORS) post request working

function textbookApi(url_link, query, username, password) {
  // console.log("INSIDE");
  console.log(makeBaseAuth(username, password));
  $.ajax({
    type: "GET",
    url: url_link,
    data: {
      'search' : query
    },
    "error": function(xhr, error, thrown) {
            console.log("Error occurred!");
            console.log(xhr, error, thrown);
        },
    beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', makeBaseAuth(username, password));
    },
    success: function(data) {
      console.log("WORKS!!!!!!!!!!!!!!!!!!!!!!!!!");
      console.log(data);
      return data;
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(url_link, status, err.toString());
    }.bind(this)
  });
}
发布评论

评论列表(0)

  1. 暂无评论