alex.mironov
alex.mironov

Reputation: 2942

XMLHttpRequest is not set by using .setRequestHeader

I try to make a cross domain request. To be able to do it I have to set an http header.

$.ajax({
                type: 'GET',
                url: 'api',
                beforeSend: function (request)
                {
                    request.setRequestHeader('authorization', 'Basic ...==');
                },
                success: function(data) {
                    debugger;
                }
            });

beforeSend method seems to be invoked but 'authorization' header is not set. Could you please help me to figure this out?

UPDATED: here are the received CORS headers:

Access-Control-Allow-Origin : localhost
Access-Control-Allow-Credential: true
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS

It looks like Access-Control-Allow-Headers is missing.

Upvotes: 3

Views: 8354

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

Make sure that your API supports CORS and that Authorization is an allowed request header to be set. When you send an OPTIONS request to the endpoint your API should respond with the following response headers:

Access-Control-Allow-Headers:X-Requested-With, Content-Type, Authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*

This allows the client to set the X-Requested-With, Content-Type and Authorization request headers when calling the API method and it allows GET, POST, PUT, DELETE, OPTIONS verbs from any origin domain.

So in order to debug the problem start by sending an OPTIONS request to your API endpoint and observe the response HTTP headers.

Upvotes: 2

Related Questions