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.
Related
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
},
...
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.
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.
I'm trying to use the Netbanx API and i always get {"error":{"code":401,"message":"Not authorised"}} I dont know what I am doing wrong.
var url = "https://api.test.netbanx.com/hosted/v1/orders";
$.ajax({
url: url,
headers: {
"Authorization": "Basic " + btoa("devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f")
},
type: 'POST',
dataType: 'jsonp',
contentType: 'application/json',
data: "{merchantRefNum:'89983943',currencyCode:'CAD',totalAmount:'10'}",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (err) {
console.log(err);
}
});
I verified your code in and receive 401 as well.
Credentials is good, I did curl request and it's return data
curl -X POST -H "Content-Type: application/json" \
-u devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f \
https://api.test.netbanx.com/hosted/v1/orders \
-d '{
"merchantRefNum" : "89983943",
"currencyCode" : "CAD",
"totalAmount" : 10
}'
{"currencyCode":"CAD","id":"27HBQC4JI28QISA1LM","link":[{"rel":"hosted_payment","uri":"https://pay.test.netbanx.com/hosted/v1/payment/53616c7465645f5f9d3670f3f61d1664e3c0db218618a55369145e7577df013ab0691c526e56a445"},{"rel":"self","uri":"https://devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f#api.test.netbanx.com/hosted/v1/orders/27HBQC4JI28QISA1LM"},{"rel":"resend_callback","uri":"https://devcentre4157:B-qa2-0-54b6431d-302c021451aabe02869ba82a4a4253d8b2a170d7950d228b021448948677e24be8180f945f1af2b583676c353b9f#api.test.netbanx.com/hosted/v1/orders/27HBQC4JI28QISA1LM/resend_callback"}],"merchantRefNum":"89983943","mode":"live","totalAmount":10,"type":"order"}
I used DHC chrome plugin for one more check - it works as well. SO I am pretty sure there is Cross Domain problem with your JavaScript example. Netbanx just does not allow to do Cross Domain request to API.
Normally in these situations the issue is how the key is encoded. it is posisble that when copying and pasting there are spaces at the beginning or end. The credentials do look valid.
The page I'm scrapping is detecting whether the request is ajax or simple one. How can I specify that ?
app.get('/gsb', function(res, req){
request({
method: 'POST',
url: "https://www.somesite.com/somepage/"
} ...
Now, this somepage detects whether its xhr or not.
Thanks
AJAX is typically indicated via the X-Requested-With header in the request.
request({
method: 'POST',
headers: {'X-Requested-With': 'XMLHttpRequest'},
url: ...})
Try that and see if it does the trick.