Nidhin VK
Nidhin VK

Reputation: 61

Cross domain jquery ajax api call with custom headers is not hitting the server

I want to call a webservice from client side using jquery ajax(with custom headers). And I almost did that. I had set Access-Control-Allow-Origin to force.com and salesforce.com since I'm calling the webservice from salesforce.

When I try to call that API without the custom headers, its getting the response where as when I called with the headers, its not getting the response.

With custom headers

jQuery.ajax({
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    url: 'https://xxx.myclient.com/xxx/xxx/register',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('orgid', '00D90000000oxxxx');
        xhr.setRequestHeader('userid', '00590000001Dxxxxxx');
    },
    success: function(response) {
        alert('success' + JSON.stringify(response));
    },
    error: function(jqXHR, textStatus) {
        alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
    }
});

also tried with

jQuery.ajax({
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    url: 'https://xxx.myclient.com/xxx/xxx/register',
    headers: {
        "orgid": "00D90000000oxxxx",
        "userid": "00590000001Dxxxxxx",
    },

    success: function(data) {
        alert(JSON.stringify(data));
    },
    error: function(jqXHR, textStatus) {
        alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
    }
});

But in both the above cases it is not hitting the server and getting the error message

enter image description here

enter image description here When I'm not using any headers, then its hitting the server

jQuery.ajax({
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    url: 'https://xxx.myclient.com/xxx/xxx/register',
    success: function(response) {
        alert('success' + JSON.stringify(response));
    },
    error: function(jqXHR, textStatus) {
        alert('jqXHR : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus);
    }
});

Its getting the success response enter image description here

In response headers it shows that

Access-Control-Allow-Headers: Content-Type

Only content-type is there, Is that the problem? Whether we need to add our custom headers here?

And when I analysed the network using firefox firebug, it is showing as given below enter image description here

  1. POST Register (without any headers passed)
  2. OPTIONS Register (with custom headers)

I dont know why this is happening

Can any one help.

Thanks in Advance ..:)

Upvotes: 2

Views: 520

Answers (1)

Manmohan
Manmohan

Reputation: 31

Try adding your custom headers (orgId and userId) in the "Access-Control-Allow-Headers" list of the service you are calling.

Upvotes: 3

Related Questions