Reputation: 78
I'm trying to get the cURL request (working via terminal on my mac) to jQuery ajax, and I'm getting a 400 BAD REQUEST. Please let me know if you see any problems with my code. This is in an attempt to use the Oanda v20 API if that helps.
cURL via terminal (working):
body=$(cat << EOF
{
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)
curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
-d "$body" \
"https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders"
jQuery ajax (not working):
$.ajax({
type: "POST",
url: 'https://api-fxpractice.oanda.com/v3/accounts/' + accountNumber + '/orders',
data: {
"order": {
"units": "10000",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + auth)
}, success: function(data){
console.log(data);
}
});
Obviously, auth
, accountNumber
, etc. are valid variables defined outside of this code.
Upvotes: 1
Views: 654
Reputation: 62566
The content-type of your request is application/json
, you should add it to the request and make sure that the content itself is sent as a string (using JSON.stringify
):
$.ajax({
...
contentType: 'application/json',
data: JSON.stringify({'order': { ... }}),
...
});
Upvotes: 2
Reputation: 3609
It might be blocked due to same-origin policy.
Have you tried with JSONP? (add dataType: "jsonp"
to your ajax call)
$.ajax({
type: "POST",
dataType: "jsonp",
url: 'https://api-fxpractice.oanda.com/v3/accounts/' + accountNumber + '/orders',
data: {
"order": {
"units": "10000",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + auth)
}, success: function(data){
console.log(data);
}
});
However, given that you're seemingly printing someone's account number into plain text JavaScript on the page, wouldn't it be more secure to send the CURL request from your own php file? Use Ajax to call your local file and then send the CURL request from there, and use the API's response to formulate your own JSON response to send back to your client side.
Upvotes: 1