Mimic Curl Headers in Ajax - javascript

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.

Related

javascript ajax POST issue

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.

How can I send a curl request from javascript?

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"
});

Access Django Rest Framework API using Javascript - getting a Token

I have an API setup using Django Rest Framework. It works fine when accessing via cURL or HTTPie or even the browsable API. The API has token authentication so initially you have to supply credentials which will return a token. Using HTTPie (or even curl) you would do this:
http POST http://127.0.0.1:8000/api/v1/api-token-auth/ username="user1" password="testpassword"
This would return a response e.g.:
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Sun, 03 Sep 2017 16:57:38 GMT
Server: WSGIServer/0.2 CPython/3.6.1
X-Frame-Options: SAMEORIGIN
{
"token": "fgfdgfdgfdgfdgd45345345lkjlj"
}
You would then take the token and perform a GET/PUSH/etc like so:
http --json POST http://127.0.0.1:8000/api/v1/test/ test_text="Testing" 'Authorization: Token fgfdgfdgfdgfdgd45345345lkjlj'
I have been Google searching for a while now and cannot find any clear answers as to how the above two lines would translate into Javascript? How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
I agree you should use Ajax.
You need an ajax call in the very beginning of you app:
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
Haven`t tested, but idea is use an Ajax call to get the token and use .ajaxSetup to save the token to a header for all following ajax requests.
The you can do this:
var data = {test_text="Testing"}
$.ajax({
type: 'POST',
data: data,
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Or this:
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/api/v1/ANOTHER_TES/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Change type parameter of the call to change your request.
See #Tico's answer.
How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
$.ajax({
type: 'POST',
data: {
username: "user1",
password: "testpassword"
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
$.ajaxSetup({
headers: {
"token": res.token
}});
$.ajax({
type: 'POST',
data: {
test_text: "Testing"
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
alert(res);
}});
}
});
as post, get or any other url calls are asynchronous calls. So in order to maintain the program flow and make the post request you need to use promise feature of js, which will make your post call synchronous.
js promise description
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
this code will work fine if you use this at the starting of your program, but this is asynchronous, to make it synchronous with your program you need to use promise.
And for the third part of your question you need to do this...
$.ajax({
type: 'GET',
url: 'http://your_url' + "/token=" + your_token,
success: function(res){
console.log(res)
},
error: function(error) {
callbackErr(error,self)
}
})

AJAX, jQuery HTTP Post, no data being recieved

I've looked at many similar questions on here, but I am unable to get to the bottom of this issue.
I've built a Web API, and if I post at it using curl as follows:
curl -i -H "Content-Type: application/json" -X POST -d '{"password":"abcd"}' http://<ip>:5000/api/v1.0/state
My API receives the message and records:
<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
{u'password': u'abcd'}
192.168.1.100 - - [08/Feb/2016 21:04:32] "POST /api/v1.0/stateHTTP/1.1" 200 -
So far so good....
I've built a webpage with the following code (I am brand new to web dev), which I am using to post against this API:
function myFunction() {
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
data: {"password" : "John"},
success: function(data){
alert(data);
}
});
}
When calling this function, the post is clearly recieved by my API, but without any data:
<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
None
192.168.1.120 - - [08/Feb/2016 21:09:53] "POST /api/v1.0/state HTTP/1.1" 200 -
I've tried using a $.post method:
$.post(
"http://" + document.domain + ":5000/api/v1.0/state",
JSON.stringify({"password" : "password" }) ,
function(data) {
alert("Response: " + data);
}
);
And I get the same result.
EDIT: Tried using the following code, as suggested by an answer below:
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
contentType:'application/json',
data: JSON.stringify({"password" : "John"}),
success: function(data){
alert(data);
}
});
And I receive an OPTIONS API response:
192.168.1.120 - - [08/Feb/2016 21:31:28] "OPTIONS /api/v1.0/state HTTP/1.1" 200 -
Any thoughts? I'm able to hit the server, but can't get any JSON data across.
Thanks!
By your curl snippet it looks like your endpoint is expecting a JSON request payload. jQuery does not set a content-type request header of application/json, so you have to actually tell it to do so:
$.ajax({
url: "http://" + document.domain + ":5000/api/v1.0/state",
method: "POST",
dataType:"json",
contentType:'application/json',
data: JSON.stringify({"password" : "John"}),
success: function(data){
alert(data);
}
});
Also note if this is being used on a different domain, meaning not "http://" + document.domain + ":5000, you may end up hitting a CORS issue.

Why am I getting 401 error for a Rails jQuery POST request?

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"}};

Categories

Resources