how to reproduce successful curl call in ajax - ajax

In Charles proxy I've captured a successful request made when using curl - which returns some json. I've tried all day to make this into an ajax call but have failed - wonder if someone could take a fresh look at it? I'm sending a token via the header to a service that provides this json
{
"category": [{
"id": 1,
"name": "aaa",
"description": "anything..."
}, {
"id": 2,
"name": "ccc",
"description": "desc 1111..."
}, {
"id": 3,
"name": "ddd",
"description": "desc..."
}]
}
charles dump of the good request made with curl
GET /api/v1/category HTTP/1.1
User-Agent curl/7.30.0
Host myurl.com
Accept */*
Authorization Token token=6ff1fed470ec2ddaf8b3af9584619902
the raw info
URL http://myurl.com/api/v1/category
Status Complete
Response Code 200 OK
Protocol HTTP/1.1
Method GET
Kept Alive No
Content-Type application/json; charset=utf-8
Client Address /127.0.0.1
Remote Address myurl.com/23.23.121.64
my attempt
$.ajax({
beforeSend: function (xhr) { xhr.setRequestHeader ('Authorization', 'Token 6ff1fed470ec2ddaf8b3af9584619902') },
type: "GET",
url: "http://myurl.com/api/v1/category",
dataType: "json"
}).done(function( msg ) {
console.log( msg );
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log( "Request failed: " + textStatus );
console.log( errorThrown );
});
thanks in advance!

You haven’t posted the diagnostics for your attempt, so I’m just going to guess from your code.
You send
Authorization: Token 6ff1fed470ec2ddaf8b3af9584619902
from XHR, but
Authorization: Token token=6ff1fed470ec2ddaf8b3af9584619902
from curl—note the token=.
You have to make sure that http://myurl.com/api/v1/category either supports cross-origin resource sharing or is located at the same origin (domain) as the page that executes that JavaScript code.
If these do not help, post whatever error messages you get.

Related

How to send form-data with RestClient, if data received from a hash?

I have an API endpoint that requires data to be sent to it as form-data. I am using RestClient for sending the data. The problem is that I do not manage to give the data for the request in a way, that the endpoint would be able to read it. This is what I have tried:
RestClient::Request.execute(
method: :post,
url: url,
payload: {
multipart: true,
data: {
"user": "test",
"phase": "test",
"job_id": "test"
}
},
headers: { Authorization: 'Basic ' + Base64.encode64(auth_details), content_type: "multipart/form-data"}
)
Any advices how I could add the hash-data for the request in a way that the endpoint could read it as a form?
EDIT1:
The endpoint does receive the request. The endpoint is written with Flask and it tries to read the form parameters using flask.request in the following way:
request.form.get("user")
I managed to get the request working by changing the reuquest to be the following:
RestClient::Request.execute(
method: :post,
url: url,
payload: {
"user": "test",
"phase": "test",
"job_id": "test"
},
headers: { Authorization: 'Basic ' + Base64.encode64(auth_details),
content_type: "multipart/form-data"}
)

Cross Origin error on ajax OAuth authentication

I'm working on a web project using microservices. When I try to access the OAuth access token from the Authentication server through an ajax call, I get an error in the browser console like this:
Access to XMLHttpRequest at 'localhost:8080/oauth/token' from origin 'http://localhost:8090' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
My Ajax
$.ajax({
url: 'localhost:8080/oauth/token',
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + auth_token
},
data: {
"username": "user",
"password": "123",
"grant_type": "password"
},
success: function(data) {
console.log(data)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I tried looking up in previous stackoverflow questions and found this similar question. But the answer doesn't work for me as I'm not loading a local file. I'm loading the model from Tomcat.
I'm just a beginner in microservices and rest api in general. Any help is appreciated.

trying to build http adapter from ajax request

i'm trying to build http adapter with token authorization form ajax request but get 401 error
Status Code:strong text
401 Unauthorized
missing_authorization
$.ajax({
type: "POST",
url: "https://abcd",
data: JSON.stringify({ "template": 1 }),
headers: { "Authorization": "xxxx", "Accept": "application/json",
"Content-Type": "application/json" }
});
function My_adapter() {
path = '/xxx';
var input = {
method : 'post',
path : path,
returnedContentType : 'json',
headers: {'Content-type':'application/json',
'Accept':'application/json', 'Authorization':'Token XXXXX'},
parameters: JSON.stringify({ "template": 1 }),
};
var result=WL.Server.invokeHttp(input);
return result;
}
tnx for your help,
sahar
The error message you see is expected. The client side code you posted shows that you are attempting to invoke MFP server outside of MFP client SDK ( jQuery ajax call). This call does not carry all the required information to the server and server sends the "missing_authorization" message as a result.
If you wish to invoke an adapter, use WLResourceRequest API provided by MFP client SDK. This takes care of handling the authentication handshake with MFP server. More details on the API usage here.

jQuery ajax() Call Failing

I am writing a web-based application that makes a call to server to update a particular object in the server, from a REST-ful application.
This is the javascript code that I have written.
var sendUrl = url + "v1/items/" + itmId;
$.ajax({
"type": "PUT",
"url": sendUrl,
//"data": {"name": nameVal, "description": descVal},
"success": function() {
alert('hai'); //refreshItems();
},
"complete": function (jqXHR, textStatus) {
alert (textStatus);
}
});
When this code is executed, the server did not receive any request. The browser did not show any update.
I am using Google Chrome as my browser. So, I looked into Chrome's Javascript Console, the console showed this error:
Are there any possible solutions to this problem?
Edit:
As suggested in one of the comments, I tried looking into Network Panel. It seems it is not making a call to Server.
This is the screenshot of this particular request:
The image is very small. The status is "(failed)" and Type is Pending
If Server does not have PUT configured, it would result in an Internal Server Error. So, that is not happening here.
Edit
After trying the suggestion given in the answer,
This is the code:
var sendUrl = url + "v1/items/" + itmId;
$.ajax({
"type": "PUT",
"url": sendUrl,
//"data": {"name": nameVal, "description": descVal},
}).done(function ( ) {
alert('OK');
}).fail(function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
Here are the objects that has been logged:
Docs for jquery Ajax function
W3 specs regarding http/1.1 status codes
First, as stated in the jQuery documentation
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
Also, the fail function accepts the following parameters:
jqXHR, textStatus, errorThrown
Since you're getting an error try the following code:
var sendUrl = url + "v1/items/" + itmId;
$.ajax({
"type": "PUT",
"url": sendUrl,
//"data": {"name": nameVal, "description": descVal},
}).done(function ( ) {
alert('OK');
}).fail(function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
This should output to the console usefull information about why the ajax call is not working.
If your webservice is working correctly, it should return a http status code. Here are some common response codes:
200 OK -> Everything is ok (it worked)
201 Created -> Ok too
400 Bad Request
401 Unauthorized
404 Not found
So, basically, the response you get should reflect why it's not working

Trigger.io Ajax Requests - with Parse Facebook User authentication

I'm trying to authenticate users from Trigger.io, ideally via Facebook.
I authenticate the user via Facebook (using the Parse Facebook module), and pass their access token, acess expiry date, and facebook Id to my call to Parse.
It is here things go wrong. Whenever I try and post this data via Ajax to the Parse REST API, I get an error in my forge/Trigger console reading:
{ type: 'EXPECTED_FAILURE', content: '{"code":107,"error":"This
endpoint only supports Content-Type: application/json requests, not
application/x-www-form-urlencoded."}', statusCode: '400', message:
'HTTP error code received from server: 400' }
The code I used to try and post this data is...
function auth(facebookId,accessToken,expirationDate) {
forge.logging.log('auth started');
forge.request.ajax({
url: 'https://api.parse.com/1/users',
headers: {
'X-Parse-Application-Id': config.parseAppId,
'X-Parse-REST-API-Key': config.parseRestKey,
'Content-Type': 'application/json'
},
type: 'POST',
dataType: 'json',
data: {
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
},
success: function (data) {
forge.logging.log('auth finished 1');
forge.logging.log(data);
},
error: function(error){
forge.logging.log('auth finished 2');
forge.logging.log(error);
}
})//success
} //auth
I can't figure out how to send this as a JSON object/ in the correct format. If anyone has any ideas they'd be much appreciated. Thanks. Josh.
Whenever the data option passed to forge.requests.ajax is an object like in your example, what actually gets posted is a query string that represents the object. The contentType option merely allows you to set the Content-Type header, it does not effect how objects are encoded for the request.
However if the data option is just a string, then this string is used as the body of the request. You can generate a JSON string to use as the body using JSON.parse like so:
forge.request.ajax({
...
contentType: 'application/json',
data: JSON.stringify({
"authData": {
"facebook": {
"id" : facebookId,
"access_token": accessToken,
"expiration_date": expirationDate
}
}
})
});

Resources