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.
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': { ... }}),
...
});
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.
Related
I am trying to store specific urls into jsonbox. However, I have been getting Error 400.
The curl command from the documentation is as below:
curl -X POST 'https://jsonbox.io/demobox_6d9e326c183fde7b' \
-H 'content-type: application/json' \
-d '{"name": "Jon Snow", "age": 25}'
Below is my edited code, putting in the link for jsonbox and URL as the data.
function send_request(url) {
this.url = url;
$.ajax({
url: 'https://jsonbox.io/box_89ad34d6d995aeb9ebb4',
type: 'post',
data: JSON.stringify(this.url),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
})
}
What am I missing or doing wrong here?
The issue seems to be the payload. Not sure why are you sending the url with your POST request. Check this working snippet:
$(document).ready(function() {
var payload = {
"name": "Maria",
"age": 78
}
$.ajax({
url: 'https://jsonbox.io/demobox_6d9e326c183fde7b',
type: 'POST',
data: JSON.stringify(payload),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
},
error: function(){
console.log("Cannot get data");
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am a problem with simple javascript web page hosted on AWS S3 that makes a HTTP POST to AWS API Gateway using ajax.
I am able to make a call using curl with success:
curl -X POST -H "Content-Type: application/json" https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta --data #data.json
data.json file:
{ "imie": "jasiu",
"ocena": "6",
"opinia": "niezle"
}
My javascript code looks like this.
<html>
<body>
<title>Ankieta</title>
<h1>Wypelnik ankiete</h1>
<button type="button" onclick="uruchom()">JSON</button>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function uruchom() {
var resultDiv = $("#resultDivContainer");
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: JSON.stringify(myData),
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
};
</script>
</body>
</html>
This is the error I get from web debug:
GET https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta?callback=jQuery17203000220305941388_1546897907447&{%22imie%22:%22Michal%22}&_=1546897908872 net::ERR_ABORTED 400
It looks like there is problem with callback and in the URL is altered with my data from body. In my case I don't want to check whenever the callback is fine - want to simply POST data.
Thanks for any suggestions.
POST can't be used to send a JSONP request. JSONP doesn't actually use AJAX, it works by creating a <script> tag whose src is the URL. There's no way to send POST data this way, so the data is added as URL parameters.
If this API expects the JSON in POST data, you can't use dataType: 'jsonp'. You have to use dataType: 'json'. If the API doesn't allow CORS, you'll need to use a proxy on your server to make the actual request, you can't do it directly from the browser.
Dont stringify the data object. JQuery does this for you. Just pass object.
var myData = {"imie": "Michal"};
$.ajax({
url: "https://xxxx.execute-api.eu-west-1.amazonaws.com/dev/ankieta",
type: "POST",
data: myData,
crossDomain: true,
contentType: "application/json",
dataType: 'jsonp',
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function () {
alert("ok");
},
error: function() {
alert("zonk");
}
});
Thanks for suggestions and answers especially in CORS direction. I was sure my API GW has CORS enabled, but didn't check AWS Lambda that is behind it and found that I was not returning "Access-Control-Allow-Origin" header back to client.
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
After applying this, I can send HTTP POST.
I would like to send this
curl https://fcm.googleapis.com/fcm/send \
-H "Content-Type: application/json" \
-H "Authorization: key=<MY API KEY>" \
-d '{ "notification": {"title": "Hello world", "body": "you got a new message", "icon": "icon/path","click_action" : "page/path"},"to" : "<DEVICE TOKEN>"}'
from a js file to wherever I want. Considering the ideas you are giving me bellow, now I'm trying with this:
$.ajax({
url: "https://fcm.googleapis.com/fcm/send",
type: 'POST',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin' : '*',
'Authorization': '<APY KEY>',
'contentType': 'application/json',
},
data: {
'title': 'Hello world!',
'body': 'you got a new message',
'icon': 'icon/path',
'click_action' : 'page/path',
'to' : '<DEVICE TOKEN>',
},
success: function (result) {
alert(JSON.stringify(data));
},
error: function (error) {
alert("Cannot get data");
}
});
but I'm getting this error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present
Curl doesn't exist in JavaScript, instead you can use XMLHttpRequest. To make it even more easy, you can use jQuery to send an AJAX request.
Here is some example code:
$.ajax({
type: "POST",
url: "http://yourdomain.com/example.php",
data: {
api_key: "xxxxxxxx"
},
success: function(data) {
console.log(data);
//do something when request is successfull
},
dataType: "json"
});
I'm using devise in a rails application. I can login to my rails server (devise) with this curl command:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/api/v1/sessions -d "{\"user\":{\"email\":\"mrezaurrahman#sample.com\",\"password\":\"3213421\"}}"
Output is like:
{"success":true,"info":"Logged in :) ","data":{"authentication_token":"8JySqFVx_pKx_3nx67AJ"}}
Now I need to access my server with javascript. This is my jquery code:
var invitation_creation = {
"email": "mrezaurrahman#sample.com",
"password": "3213421"
}
$.ajax({
url: "http://localhost:3000/api/v1/sessions.json",
type: "POST",
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr("content"))},
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(invitation_creation),
success: function(){ console.log("success")}
});
But now I'm getting following error:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
I already have a user who has email "mrezaurrahman#sample.com" and password "3213421".
I can log in using curl, but I can't use my javascript code.
How can I log in to this system using javascript?
Could you please try to use this:
var invitation_creation = { "user": {
"email": "mrezaurrahman#sample.com",
"password": "3213421"
}}
instead of
var invitation_creation = {
"email": "mrezaurrahman#sample.com",
"password": "3213421"
}
I had problem with JSON creation. The invitation_creation JSON declaration line would be like,
var invitation_creation = {"user":{"email":"mrezaurrahman#live.com","password":"28902890"}};
I'm trying to mimic this curl command to an ajax call.
curl -H 'X-Auth-Id' 'someid' http://someurl.com/api/posts
I've tried using
$.ajax({
url: 'http://someurl.com/api/posts',
type: 'get',
headers: {
'X-User-Id': userId
},
success: function(data) {
console.log(data);
}
});
But I seem to be getting an Invalid status code error, which I do not get when using curl from bash.