I am trying to complete a GET request using $http instead of ajax. The call works perfectly with ajax, but when I try to do the same thing with $http I get a 400 (Bad Request) error. I believe I am following the Angular documentation correctly. Any ideas? Hopefully this will also be helpful for others experiencing the same issue.
The ajax code that works:
$.ajax({
type: "GET",
accept: 'application/json',
url: myURL,
headers: {"Authorization": "Basic " + basicKey},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
data: requestPayload,
async: false
}).done(function(serverData) {
console.log(serverData.access_token);
}).fail(function(error) {
console.log(error);
});
The $http code that does not work:
var basicConfig = {
method: 'GET',
url: myURL,
headers: {
'Authorization': 'Basic ' + basicKey,
'Accept': "application/json",
'Content-Type': 'application/x-www-form-urlencoded'
},
data: requestPayload
}
$http(basicConfig).success(function(data, status){
console.log(status);
}).error(function(data, status){
console.log(status);
});
Thanks in advance.
use params instead of data. data is the request body, used for POST requests, whereas params is for query string variables in GET requests.
Related
i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs.
We received now an API Token to call for the data on the framework.
I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)".
$.ajax({
type: 'POST',
headers: {
'X-CSRFTOKEN': "XXXXXXXXXXXXXXX",
'Content-Type': 'application/json'
},
url: 'www.service-provider.url/api/...',
success: function () {
console.log("ok");
},
error: function () {
console.log("error");
}
});
Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work.
Okay i got it! Before the token api key there must be "Token ...".
$.ajax({
type: 'GET',
url: 'https://my-url.com/api/1.0/?format=json',
headers:{
"Content-Type": 'application/json',
"Authorization": 'Token XXXXXXXXXXXXXXXXXXXXX',
},
success: function(data){
console.log(data);
}
});
I am using HTTP POST request to give notification to authors on my web-app that their stories are approved by our admin.
My payload looks like this
var payload = {
"notification": {
"title": "Story Approved!",
"body": "Your story is approved"
},
"to" : to
}
This is my request
$.ajax({
type: 'POST',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': 'key='+serverKey
},
data: payload,
success: function(response){
console.log(response);
},
});
Whenever I try to send the request it gives me the following error
POST https://fcm.googleapis.com/fcm/send 400 ()
I am kinda new to this and according to Firebase Error Response Codes
Invalid JSON 400 Check that the JSON message is properly formatted and contains valid fields (for instance, making sure the right data type is passed in).
But I cannot figure out where I am wrong. Any help would be appreciated
just convert your payload to json like this:
data: JSON.stringify(msg)
and your code will be like this:
$.ajax({
type: 'POST',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Content-Type': 'application/json',
'Authorization': 'key='+serverKey
},
data: JSON.stringify(msg),
success: function(response){
console.log(response);
},
});
I'm trying to upload data to dropbox via webbrowser (FF 42.0, PhantomJS 1.9.8) and dropbox v2 api. My function looks like this
function(path, data, callback) {
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
contentType: 'application/octet-stream',
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
},
data: data,
headers: {
"Authorization": "Bearer " + token,
"Dropbox-API-Arg": '{"path": "' + path + ',"mode": "add","autorename": true,"mute": false}',
"Content-Type": "application/octet-stream"
},
success: function (data) {
callback(data);
}
});
}
Even I set the Content-Type at all attributes I can think of to application/octet-stream I get the following error
Error in call to API function "files/upload": Bad HTTP "Content-Type" header: "application/octet-stream
; charset=UTF-8". Expecting one of "application/octet-stream", "text/plain; charset=dropbox-cors-hack"
Taking a look at the request in Firebug shows me that the Content-Type was really set to application/octet-stream; charset=UTF-8. When trying text/plain; charset=dropbox-cors-hack as Content-Type the sent request has text/plain; charset=UTF-8, and I get the same error message.
How can I make jquery and my browser to set the headers I need.
EDIT: Same behavior in Chrome
IE works as expected
Technically, Firefox is just adhering to the W3C XMLHttpRequest spec:
http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
Sending anything other than a Blob or ArrayBufferView can cause issues with browsers attempting to encode the data in UTF-8 (to follow the spec).
The right thing to do here is to avoid sending data as a String. Here are two examples of how to avoid this behavior:
// ... file selected from a file <input>
file = event.target.files[0];
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: file,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Or, if you want to send up text, you can UTF-8 encode the text before uploading yourself. A modern way to do this is using TextEncoder:
var data = new TextEncoder("utf-8").encode("Test");
$.ajax({
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: data,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer " + ACCESS_TOKEN,
"Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
}
})
Try this...
private void upload(object sender, EventArgs e)
{
OAuthUtility.PutAsync
(
"https://content.dropboxapi.com/1/files_put/auto/",
new HttpParameterCollection
{
{"access_token",Properties.Settings.Default.AccessToken},
{ "path", Path.Combine(this.CurrentPath, Path.GetFileName(openFileDialog1.FileName)).Replace("\\", "/") },
{ "overwrite","false"},
{ "autorename","false"},
{openFileDialog1.OpenFile()}
},
callback : Upload_Result
);
}
I am trying to make an AJAX call to an API which requires an HTTP header (REST parameters).Currently no data is being returned. I think what is giving the most difficulty is understanding setRequestHeader, not even sure if its necessary. In this example , msdn it takes 2 string arguments: oReq.setRequestHeader("Content-Type", "text/xml") but then where does the authorization header go? Please Help
Currently I have this:
var baseURL = "https://api.azuga.com/azuga-ws/v1/live/location.json";
var header = "Authorization: Basic 0JRGDJW587832"; //Made up number
$.ajax({
url: baseURL,
dataType: 'json',
beforeSend: function(xhr){xhr.setRequestHeader(header);},
success: function(data){
console.log(data);
}
});
Did you tried:
var baseURL = "https://api.azuga.com/azuga-ws/v1/live/location.json";
$.ajax({
url: baseURL,
dataType: 'json',
headers: { 'Authorization': 'Basic 0JRGDJW587832' },
beforeSend: function(xhr){xhr.setRequestHeader(header);},
success: function(data){
console.log(data);
}
});
?
also note that your header is a string, so setRequestHeader is not taking two parameters!
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: { Authorization: "Basic " + btoa('myusername' + ":" + 'mypassword#123') },
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
I am trying to get access token from bitly api by providing username and password but it is showing invalid_client_authorization error. Does any one have idea on the same?
Bitly documentation : http://dev.bitly.com/authentication.html#resource_owner_credentials
You are concatenating your username with your authorization header.
Your authorization and content-type should go in the headers object.
There is no 'type' property on jquery ajax method, you probably meant 'method'.
Also, you can't send both dataType:'json' and set the content-type to 'application/x-www-form-urlencoded'
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
methdo: 'POST',
contentType: '',
dataType: 'json',
headers: {
'Authorization' : 'Basic ' + [INSERT YOUR HASH HERE],
'Content-Type' : 'application/x-www-form-urlencoded',
}
data: { $.serialize({
username: YOURUSERNAME,
password: YOURPASSWORD
})},
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
This should do it
Fixed #goncalomarques answer:
Removed top level "contentType" and "dataType"
Removed data object (otherwise username and password is sent as clear text, in addition to the hashed username and password in the header)
renamed "methdo" to "method"
Explicitly used btoa() to get Base 64 encoded hash (be aware, does not work in older IE versions)
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(YOURUSERNAME + ':' + YOURPASSWORD),
'Content-Type': 'application/x-www-form-urlencoded',
},
success: function(result) {
console.log("success");
console.log(result);
},
error: function(response) {
console.log("Cannot get data");
console.log(response);
}
});
Note:
I have this example working, but was unable to get it working with the built-in Stackoverflow editor ("Run snippet") due to cross origin exceptions.