0

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?

user3766930
  • 5,629
  • 10
  • 51
  • 104

1 Answers1

3

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.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • I changed `http://example.com/mail` to `//mail` and now I'm getting error: `jquery-1.10.2.js:8706 POST http://mail/ net::ERR_NAME_NOT_RESOLVED`.. what am I doing wrong here? – user3766930 Jun 25 '16 at 15:00
  • @charlietfl http://stackoverflow.com/questions/4071117/uri-starting-with-two-slashes-how-do-they-behave – Pointy Jun 25 '16 at 15:04
  • @user3766930 sorry charlietfl is correct; I'll edit the answer. – Pointy Jun 25 '16 at 15:05