I am writing a quotation system for myself.
I have this web page for quotations, which does:
a) send an email to the customer (done) with the quoted items
b) create a record inside a google spreadsheet (done)
c) create a task in asana (fail)
For the last 2 days I have been surfing and reading all I can find, but the solution skips from my mind.
This is the CURL code, which works just fine:
curl -H "Authorization: Bearer 0/7alotofnumbers" \
https://app.asana.com/api/1.0/tasks \
-d "projects=83694179XXXXXX" \
-d "tags[0]=269280227XXXXXX" \
-d "assignee=sales#atmysite.com.mx" \
-d "due_on=2017-02-09" \
-d "name=testing with curl" \
-d "notes=it works just as expected" \
-d "followers[0]=myself#atmysite.com.mx"
Now, I translated the CURL command that WORKS into asanataskcreate.coffee:
$.ajax
url: 'https://app.asana.com/api/1.0/tasks'
beforeSend: (xhr) ->
xhr.setRequestHeader 'Authorization', 'Bearer 0/7alotofnumbers'
return
contentType: 'application/json'
method: 'get'
data:
projects: [ 83694179XXXXXX ]
tags: [ 269280227XXXXXX ]
assignee: 'sales#atmysite.com.mx'
due_on: '2017-02-09'
name: 'testing with js ajax'
notes: 'it does not work'
followers: [ 'myself#atmysite.com.mx' ]
which turns into asanataskcreate.js:
$.ajax({
url: 'https://app.asana.com/api/1.0/tasks',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer 0/7alotofnumbers');
},
contentType: 'application/json',
method: 'get',
data: {
projects: [83694179XXXXXX],
tags: [269280227XXXXXX],
assignee: 'sales#atmysite.com.mx',
due_on: '2017-02-28',
name: 'testing with js ajax',
notes: 'it does not work',
followers: ['myself#atmysite.com.mx']
}
});
And, FAILS :(
Ok, I have tried:
a) method: 'post' and 'get'
b) place, remove the '[]' at projects, tags and followers
With the assistance of Chrome devtools in the 'console' I get the following message:
Failed to load resource: the server responded with a status of 400 (Bad Request)
and
XMLHttpRequest cannot load https://app.asana.com/api/1.0/tasks?projects%5B%5D=836941797XXXXXX&tags%5B%5…¬es=it+does+not+work&followers%5B%5D=myself%40atmysite.com.mx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://atmysite.com.mx' is therefore not allowed access. The response had HTTP status code 400.
Now, in DevTools, when checking the XHR response from asana, this is what I get:
message: "You should specify one of workspace, project, tag, section"
As you can see from the code, there is a project id defined, but in JS fails and in curl works.
Analyzing why 'projects' in curl works and in ajax fails, the difference is:
curl: projects=83694179XXXXXX
js ajax: projects%5B%5D=836941797XXXXXX ==> projects[]=836941797XXXXXX
What I am doing wrong?
Here is an example of an Ajax request that creates an Asana task:
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + "0/0123...");
},
url: "https://app.asana.com/api/1.0/tasks",
method: 'POST',
data: {projects:123456789, name: "ajax created task"},
});
It's uncertain how much of your compiled Ajax code is wrong. You definitely need to use a POST request to create a new task. The data values should not be in arrays. You likely don't need to list contentType, as the default will work. You should be able to get your code in working order based on my example.
You should also be aware that by using Ajax, you're exposing your Personal Access Token in the client. If you see anything suspicious on your account, you may want to delete that PAT.
Related
Is it possible to make a curl request by using axios?
the curl string is:
curl -v 'https://developer.api.autodesk.com/authentication/v1/authenticate' --data 'client_id=1234&client_secret=1234&grant_type=client_credentials&scope=bucket:create bucket:read data:write data:read viewables:read' --header 'Content-Type: application/x-www-form-urlencoded' -k | jq '.'
I tried to do this:
getToken() {
axios.get({
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
data: {
client_id: '1234',
client_secret: '1234',
grant_type : 'client_credentials',
scope: 'data:read data:viewables'
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}, success: function(data){
console.log(data)
}
})
}
But with no luck - e.g. nothing happens.
I previously used the cygwin-terminal to make the curl-request and I succesfully got the response
{
"token_type": "Bearer",
"expires_in": 1799,
"access_token": "eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5X2RldiJ9.eyJjbGllbnRfaWQiOiJjWTFqcm1rQXhPSVptbnNsOVhYN0puVURtVEVETGNGeCIsImV4cCI6MTQ4NzU2NzgwMSwic2NvcGUiOlsiZGF0YTpyZWFkIl0sImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9qd3RleHAzMCIsImp0aSI6InJZcEZZTURyemtMOWZ1ZFdKSVVlVkxucGNWT29BTDg0dFpKbXlmZ29ORW1MakF0YVVtWktRWU1lYUR2UGlnNGsifQ.uzNexXCeu4efGPKGGhHdKxoJDXHAzLb28B2nSjrq_ys"
}
So, is this possible with React/axios?
In addition to the question, can I pass the received token to another curl request?
Well it's not really "a curl request". It's an HTTP request. Curl is just the tool you use to do HTTP (and other) actions via the command line.
In your HTTP request, I can see you're using axios.get(), however you're trying to do a post request (you've got a data object you're trying to send). So you should be using axios.post(). It'd be best to check out the axios page to see the syntax for HTTP posts, including how to include the data and header objects in the post.
In answer to your second question, yes you can. In the .then() section of your first axios post, you can do another axios post using the response, e.g.
axios.post(
...
).then(response => {
// do another post with response.token or whatever as the data
})
...
I am trying to delete user with scim service.
When I call it through SoapUI and curl it works but when I create ajax call it returns 405 method not allowed
SOAPUI5
IP:
https://localhost:9447//wso2/scim/Users/token_of_user_to_be_deleted
OAUTH2 token: my_token_for_oauth
Media type: application/json
CURL
curl -v -k --user admin:admin -X DELETE https://localhost:9447/wso2/scim/Users/b228b59d-db19-4064-b637-d33c31209fae -H "Accept: application/json"
This both worked and deleted the user.
AJAX DOESNT WORK FOR ME
$.ajax({
url: 'https://localhost:9447/wso2/scim/Users/token_of_user_to_be_deleted',
type: 'DELETE',
headers: { 'Content-Type':'application/json'},
xhrFields: {
withCredentials: true
},
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Bearer ' + that.oauth2.loadToken().access_token);
},
success: function() {
console.log("success")
},
error: function () {
console.log("error")
}
});
ERROR:
Cross-Origin Resource Sharing (CORS) Filter: Unsupported HTTP method: DELETE
The browser does hit an OPTIONS request before sending the actual request. This request includes the accepted methods
Access-Control-Allow-Methods: GET, OPTIONS
Your server does not send a DELETE accepted method in the options response, hence your request throws this error.
To solve this issue, you need to add the DELETE to the accepted methods by your server. in your server settings
Access-Control-Allow-Methods: POST, GET, DELETE, OPTIONS
The options request is only sent on the browser since it is only implemented by the browsers as a security measure. curl / node / SOAPUI5 do not confirm to this restriction, hence enable you to get what you want. (unless the server is configured otherwise internally to prevent some headers)
Update
As #jannis mentioned, It's worth noting that the OPTIONS request preceding the actual one is called a preflight request and the mechanism in general is called CORS.
You can read more in preflight requests (and CORS in general) by following these links:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control#Preflighted_requests
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
I have a curl command for getting json data and I want to send this request from javascript program. Please anybody can tell how to convert this curl command into jquery ajax request.
Command:
curl -H "Snapdeal-Affiliate-Id:<your affiliate ID>" -H "Snapdeal-Token-Id:<your affiliate Token>" "<URL for the chosen category>" -H "Accept:application/json"
cURL -H parameters add extra headers to the request.
jQuery.ajax have an option headers, this is a Plain JavaScript Object with the pair name/value for each header.
Then, your cURL request will translate in something like this:
$.ajax(url, {
url: "<URL for the chosen category>"
headers: {
"Snapdeal-Affiliate-Id":"<your affiliate ID>",
"Snapdeal-Token-Id":"<your affiliate Token>"
},
accepts: "application/json"
}).done(function (data) {
// code to handle succesful response
}).fail(function (data) {
// code to handle error response
});
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.
I have an cURL call that works and I have converted it to an ajax call. The ajax call is failing. How do I get something to return from the call? There should be a dictionary [cURL call returns a dictionary].
How do I know what is failing in my call? I don't know how to proceed in debugging it.
Thanks
curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:pass https://my.address.for/this/url -d "{\"name\": \"Marcus0.3\",\"start\": 500000,\"end\": 1361640526000}"
$.ajax({
type: 'put',
url: 'https://my.address.for/this/url',
dataType: 'json',
async: false,
username: 'user',
password: 'pass',
data: {
"name": "Marcus0.3",
"start": 500000,
"end": 1361640526000
},
success: function(){alert('DONE!');},
error: function(){alert('fail');},
}).responseText;
I keep getting 'fail' responses
If you type F12 it will open up chrome dev tools, then click on the network tab.
You will see all requests, including ajax requests as they happen. You can click on the line item "name" field for full info about the request and response, similar to cURL verbose mode
You can use Firefox with firebug to get the exact error message.Else do like this
error:function(error){alert(error)}