Not able to send header with xhrfield - javascript

I am trying to get flipkart api data . like this but i am not able to send heder with xhrfield
HERE IS MY CODE :
$.ajax({
type: 'GET',
url:'https://affiliate-api.flipkart.net/affiliate/search/json?query=iPhone+mobiles&resultCount=3',
crossDomain: true,
// dataType: 'JSONP',
/*xhrFields: {
withCredentials: true
},*/
// contentType: 'application/json; charset=utf-8',
beforeSend : function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader('Fk-Affiliate-Id', 'myid');
xhr.setRequestHeader('Fk-Affiliate-Token', 'mytoken');
},
/* headers: {
'Access-Control-Allow-Origin':'*',
'Fk-Affiliate-Id': 'myid',
'Fk-Affiliate-Token': 'mytoken',
'Content-Type': 'application/x-www-form-urlencoded'
},*/
success: function(data){ ......
}
});
As you can see comment i ahve tried both but not able to send header with xhrfield . if i comment xhrfield header wil be send

You can not send a header with a JSONP requests since all it does is set a script tag to the page.
A JSONP requests consists of appending a script tag to the page. It adds a callback parameter to the URL which the script listens for when the script is executed. There is no way to add the header to a external script.
The site would need to support JSON request for CORs to send the header.

Related

Custom headers are not sent with my AJAX requests

I am trying to make an AJAX request from my client to my NodeJS/ExpressJS backend.
However, when the request is fired, my backend receive it well but doesn't recognize the custom headers . e.g.
$.ajax({
type: "POST",
url: "/foo",
headers: {"authorization": "Bearer 12345"},
data: formData,
dataType: "json",
encode: true,
})
in Node , when I do req.headers['authorization'] I get undefined.
I don't understand what I did wrong.
Any advice ?
I'm not sure whether the request you're making is cross-url or not, but if it is try the following:
$.ajax({
url: "yoururl",
type: "GET",
dataType: 'json',
xhrFields: {
withCredentials: true // edited
},
//...
});
I ran into the same error a few times before and it was due to me not adding this important attribute to the request - when authentication is required.

How to send OPTIONS Method call to server via ajax jquery/javascript?

I am trying to call an API that accepts OPTIONS method on server, it runs on postman and returns json object but following code is not working on js
I have read that OPTIONS call is a preflight call for CORS calls, so this API is https and on another server. But even then there is no response and it returns 405 method not found
$.ajax({
url: url,
dataType: "jsonp",
method :"OPTIONS",
crossDomain: true,
contentType: 'application/json',
headers: {
"Content-type": "application/json",
"Cache-Control": "no-cache",
"Accept": "application/json,long_format",
"Access-Control-Allow-Origin": "*"
},
success: function (data) {
console.log("success" + data);
},
error: function (data) {
console.log("fail" + data);
}
}).fail(function(data) {
console.log("failed" + data);
});
Extra info :
The API is cross domain and on ssl so to cover cross domain request I had to user dataType: "jsonp"
UPDATED :
This is impossible scenario so I have to get update on server end...
Explanation:
There is some problem with
OPTIONS method that is behind cross domain as well
a/c to some research i have done on internet, CORS request can be accessed with :
dataType: "jsonp",
but with -> dataType: "jsonp"
you can only call GET methods
so we are stuck here that allows that either we call cross domain https request or we can call OPTIONS method,
usually OPTIONS method is a preflight method done automatically by browser
NOW please stop down voting my question
dataType: "jsonp",
Take this out. JSONP requests are always GET requests. This is your main problem.
crossDomain: true,
Take this out. It does nothing unless you are making a same origin request that gets redirected to be a cross origin request.
contentType: 'application/json',
Take this out. You are making an OPTIONS request. There is no request body to describe the content-type of.
"Content-type": "application/json",
Take this out. For the same reason.
"Access-Control-Allow-Origin": "*"
Take this out. It is a response header and has no place on the request.

Javascript POST to API

So I am a bit lost and hoping you can help me out. I am writing an app in simple PHP/HTML/Javascript app.
My Goal: To POST json data to an API.
How can I go about this? I just can't find any good examples to show me the best way to handle this.
In my request I need to send Basic Authorization as well as the json values.
This is what I have right now
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
success: function (){
alert('Comment Submitted');
}
});
I can't get the above code to work. Im using a button to call a function that will start the ajax call but nothing is happening.
Any help be be amazing! Thank You.
Use
contentType:"application/json"
You need to use JSON.stringify method to convert it to JSON format when you send it,
And the model binding will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
If you're writing the API in PHP, and it uses $_POST to get the parameters, you shouldn't send JSON. PHP only knows how to decode multipart/form-data and application/x-www-form-urlencode. If you pass an object to $.ajax, jQuery will use the urlencode format.
Just take the quotes off the object that you're passing to the data: option.
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
success: function (){
alert('Comment Submitted');
}
});
You also shouldn't use async: false, it is deprecated. Learn to write proper async code.
Nobody seems to have addressed one issue - the URL
If the page this is requested from is http://yourhost.com/path/file.html the request will be sent as http://yourhost.com/path/host.com/api/comments
As you have host.com in the URL, I assumed the request is to a different domain?
use one of
http://host.com/api/comments
https://host.com/api/comments
//host.com/api/comments
will only work if your page is loaded http and not https
will work only if the remote API supports https
will only always work properly if the remote API supports both http and https
The other issue is regarding the format of the sent data
The default content-type for $.ajax POST is application/x-www-form-urlencoded; charset=UTF-8
So, sending a POST request with various combinations of contentType and data shows the following
Firstly, without setting contentType
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
request is sent as formData '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
request is sent as formdata, the following values:
value1: 2.0
value2: setPowerState
value3[state]: 0
looks better, because there's actually multiple values, not just a string
Now, let's set contentType
contentType: 'json', data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
firefox does not tell me the format of the following string: 'value1=2.0&value2=setPowerState&value3%5Bstate%5D=0' - looks useless
And finally
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
sends the following JSON: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
So, finally, if the API requires JSON request data, and it's actually on a domain called "host.com"
$.ajax({
type: "POST",
url: "//host.com/api/comments",
dataType: 'json',
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
});

Unable to receive request headers from jQuery AJAX in Mule

I have a Mule flow and I'm trying to send custom request headers using an AJAX call from html files placed on my system (html files are not on the server).
The following code doesn't work:
$("#submit").click(function(){
$.ajax({
url: "http://localhost:8081",
crossDomain: true,
headers: {
Accept : "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
"myHeader" : "myHeaderValue"
},
method: 'GET',
data: { hello : "hello" }
}).complete(function(data) { alert(data); });
});
I've tried using async:false, cache:false, content-type etc but nothing works. All I get from Mule is this:
I've added this in the Mule-flow but it still doesn't seem to work:
<set-property propertyName="Access-Control-Allow-Origin" value="*" />
I've tried hitting the same flow from Java code, Python, Postman and the same header from all sources was received in Mule with value, but AJAX it fails on.
Thanks.

AngularJS can't send post request with Content-Type:application/json

Currently I am using angularJS and CoffeeScript to try to send a post request, and my sample code is:
login: (user, callback)=>
baseUrl = 'http://localhost:3000/api/v1/sessions'
#$http({
method: 'POST',
url: baseUrl,
data: user
}).success (result)->
callback(result)
But when I call it, it just send 'OPTIONS' request instead of POST request.
And the request detail is:
If I add header to this method,
login: (user, callback)=>
baseUrl = 'http://localhost:3000/api/v1/sessions'
#$http({
method: 'POST',
url: baseUrl,
data: user,
headers:
'Content-Type': 'application/json'
}).success (result)->
callback(result)
It still doesn't works, but if I change headers to 'Content-Type': 'application/x-www-form-urlencoded', then it can send post requests.
But the request Content-type is not not I want.
I also try to modify the request data to JSON by: data: JSON.stringify(user), but still not working.
UPDATES
Guys, I did another spike on this issue. Which is I am jquery to send the request and it works fine, but I found an wired thing that is they have different request data.
Jquery
$.ajax({
type: "POST",
url: "http://localhost:3000/api/v1/sessions",
data: {
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
},
success: function(){
}
Screenshot for Jquery
Angular
login: (user, callback)=>
baseUrl = 'http://localhost:3000/api/v1/sessions'
#$http({
method: 'POST',
url: baseUrl,
data: {
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
},
headers:
'Content-Type': 'application/x-www-form-urlencoded'
}).success (result)->
callback(result)
Now it can send request,but I just got 401 when trying to do request.
Screenshot for Angular
So I think the issue may due to the format of the angular request data.
You are hitting CORS restrictions and same origin policy.
Easiest solution is to deploy web frontend and the api together as one app. If ports are different even on the same machine then one needs to deal with same origin policy.
Options is a preflight query. Make your backend accept it and it should be fine.
More reading:
http://www.html5rocks.com/en/tutorials/cors/

Categories