Get 401 when using ajax call to retrieve data from couchdb - javascript

I try to use ajax call in js file to retrieve data from couchdb.
But I got the 401 error:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Here is my js code:
var locate_data = $.ajax({
url: 'http://admin:mypassword#localhost:5984/database_name',
type:'GET',
dataType: "json",
success: function(data){
console.log("successfully loaded."),
alert(data);
},
error: function(xhr) {
console.log("error"),
alert(xhr.statusText)
}
})
I can use 'curl GET' to get the data from couchdb by using the terminal.
What is the problem? and how can I fix it?

You could use Basic access authentication where requests contain a header field in the form of Authorization: Basic <credentials>, where credentials is the Base64 encoding of username and password, joined by a single colon ':'.
This answer explains how to do the same in the context of Angular. I'm not using Ajax myself but I suppose it should look something like this.
$.ajax({
url: 'http://localhost:5984/database_name',
type:'GET',
headers: {
'Accept': 'application/json',
'Content-type', 'application/json',
'Authorization': 'Basic ' + btoa("<username>:<password>")
},
xhrFields: {
withCredentials: true
},
...

Related

in Ajax, how to write "headers" for multiple condition?

as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});
You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.

Trying to Convert jQuery ajax to ES6 fetch

In an effort to not use jQuery (if ajax is all I need it for) I have the following ajax call that works like a champ.
$.ajax({
type: "POST",
url: "/Tests/EEG/Portable/Index?handler=Testing",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success");
},
failure: function (response) {
alert(response);
}
});
I rewrote it in standard javascript using fetch as follows:
fetch("/Tests/EEG/Portable/Index?handler=Testing", {
method: "POST",
headers: {
'XSRF-TOKEN': $('input:hidden[name="__RequestVerificationToken"]').val(),
'content-type': 'application/json; charset=utf-8'
},
body: JSON.stringify(model)
}).then(checkStatus)
.then(function (data) {
alert("second then");
}).catch(function (error) {
console.log(error);
});
Which gives me the following error:
Failed to load https://stubidp.sustainsys.com/xxx?SAMLRequest=xxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:58659' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Which leads me to add the following attribute:
mode: 'no-cors'
Which gives me the following warning (and does not get to my backed method)
Current.js:78 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://stubidp.sustainsys.com/xxx?SAMLRequest=xxx&RelayState=q-9E0I4hwfJLlInurXY-Yu4g with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Which lead me to add the following:
'X-Content-Type-Options': 'nosniff'
Which gave me the same warning and still did not get to my server.
Any thoughts on what I am still missing?
Update
While looking around the Network tab on Chrome's debugger tools, I noticed the Copy as fetch option. I did this on the working jQuery call and gave me the following JavaScript:
fetch("http://localhost:58659/Tests/EEG/Portable/Index?handler=Testing", {
"credentials": "include",
"headers": {},
"referrer": "http://localhost:58659/Tests/EEG/Portable",
"referrerPolicy": "no-referrer-when-downgrade",
"body": JSON.stringify(model),
"method": "POST",
"mode": "cors"
});
When I run that fetch method I get a 400 Bad request error.
I would say that thanks to #Wesley Coetzee that got the ball rolling in the right direction. What took care of it for me was the following code:
fetch('/api/Tests/Single', {
credentials: 'include',
headers: {
'XSRF-TOKEN': $('input:hidden[name="__RequestVerificationToken"]').val(),
'content-type': 'application/json; charset=utf-8',
'X-Content-Type-Options': 'nosniff'
},
referrer: '/Tests/EEG/Portable',
referrerPolicy: 'no-referrer-when-downgrade',
body: JSON.stringify(model),
method: 'POST',
mode: 'cors'
});
A little back story in case that helps: Everything in the question was based on trying to POST to an ASP.Net Core RazorPage event. After some realization between this new project we are starting and the extra pain you have to go through (not the above code) to convert a response to an actual entity, we changed to using WebAPI. The code in this answer is going to a WebAPI controller and no longer a RazorPage method.
Hope it helps someone.

Access MailChimp API 3.0 (GET)

I'm trying to make a GET request through jQuery to the Mailchimp API. It seems though my custom header is not correctly set as I get a Your request did not include an API key. error.
It works fine if I make the request using curl on my Ubuntu machine:
curl --header "Authorization: apikey 709XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us11" https://us11.api.mailchimp.com/3.0/campaigns
Here's my code:
$.ajax({
type: 'GET',
url: 'https://us11.api.mailchimp.com/3.0/campaigns',
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
headers: {
'Authorization': 'apikey 709XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us11'
}
}).done(function (response) {
console.log(response); // verbose
});
I even tried adding this above:
$.ajaxSetup({
headers: { 'Authorization': 'apikey 709XXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us11' }
});
You need to add the key via Basic Auth like and as far I am aware off, You can't query it from front-end, it must be on the back-end.
Find an example in NodeJS:
headers: {
'Authorization': 'Basic ' + new Buffer(`anything:${MailChimpKey}`).toString('base64');
}
MailChimp not allowed to direct access with ajax. Once make Server WebRequest. It will surely work.

How to pass authorization header in $.post() method using Javascript?

I want to pass Authorization header while POSTing data to server.
I tried
$.ajax({
url : <ServiceURL>,
data : JSON.stringify(JSonData),
type : 'POST',
contentType : "text/html",
dataType : 'json',
success : function(Result) {
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', <Authorization Header Value>);
},
error: function (RcvData, error) {
console.log(RcvData);
}
});
But REST service returns error (error code : 500). The same service was working fine with $.post() before adding authorization.
could anyone tell me "How to pass authorization header in $.post()??"
Use
contentType: 'application/json',
You may have gotten data and contentType mixed up.
contentType is the Content-type header you send.
data changes how jQuery treats the data you receive.
The jQuery $.ajax() method accepts a headers value in the settings object.
So:
$.ajax({
// url, data, etc...
headers: {
"Authorization" :"Basic " + myBase64variable,
"Content-Type" :"application/json"
}
});
Source: http://api.jquery.com/jquery.ajax/
PS: Seems you can also pass in a new settings object in the beforeSend parameter. I didn't know this, so thanks for asking this question :)

xhr.getAllResponseHeaders() returns only one header

We have Node.js as a server which helps in getting us remote rest service, from client html I am trying to get response headers from the jQuery Ajax call using below code:
$.ajax({
type: "get",
url: newUrl,
crossDomain: true,
cache: false,
dataType: "json",
contentType: "application/json; charset=UTF-8",
success: function(data, textStatus, xhr) {
var responseText = JSON.stringify(data);
alert(xhr.getAllResponseHeaders());
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
But the problem is, I only get one one response header: Content-Type: application/json remaining things are ignored. From my research I found that I need to add Access-Control-Allow-Headers to make that available. So in Node I tried like this:
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Origin'
});
But still I get only the one header Content-Type. Can you help in identifying this issue? By the way, it's a cross domain calls.
Finally I am able to resolve this issue, from the Node.js side.
I added both
Access-Control-Expose-Headers and Access-Control-Allow-Headers
to the response header in node.js. This solved my issue. Earlier I was having only Access-Control-Allow-Headers.
What header do you want? Add it to Access-Control-Allow-Headers. (I'm not sure whether CORS header show up or not, though you probably won't need them.)
'Access-Control-Allow-Headers': 'Header1, Header2, Header3'

Categories

Resources