user3766930 user3766930 - 5 months ago 9
Ajax Question

No 'Access-Control-Allow-Origin' header when accessing webpage address starting from www. Without www it works - why?

I have a webservice in my node.js web app (placed on amazon ec2) and it takes email address and saves it to mongodb. This webservice is placed on

/mail
of my server.
I wrote a small ajax code that sends the data directly to the webservice.
It looks like this:

$.ajax({
url: 'http://example.com/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response)
{
var output = '<p style="color: white">Thanks, we will be in touch!</p>';
form.find("#form_results").hide().html(output).slideDown();
}
});


When in browser I enter my page by typing http://example.com and provide email - everything works fine. But when I add
www
and enter my webpage as www.example.com - then after trying to send email I'm getting a well known error:

XMLHttpRequest cannot load http://example.com/mail.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://www.example.com' is therefore not allowed access.


How can I change my ajax code (or any other possible parts of code) so that I can submit email either from
http://
or
www
pages?

Answer

The access control rules consider the URL method ("http" or "https"), the whole domain name, and the port number. The rules don't "think" about the URL; it's a straight textual comparison.

Thus, "www.example.com" and "example.com" are considered two distinct domains, and so cross-origin rules apply.

You can use the URL "/mail" in your $.ajax() call instead, which will use the same method and domain and port as the containing page.

(Edited - I was confused or undercaffeinated or both. Should be "/mail" with one slash.)