Making a post request from a sinatra app to a rail

2019-07-30 19:14发布

问题:

I need to send a POST request from a sinatra app to a rails app which would return back some json. Im testing this functionality locally. The urls are as follows:

Rails app : railsapp.mydomain.com/api/v1.json
Sinatra app: sinatraapp.mydomain.com

On localhost, the urls are:

Rails app: localhost:3000/api/v1.json
Sinatra app:localhost 3001

In my sinatra app running locally, i have the following code to make the POST request locally

$("#submit").click(function(){
   $.post("http://localhost:3000/api/v1.json",
     {email:"<email_here>",password:"<password_here>"},
     function(data) {
         //Do something with response
     }
   );

});

Also, the Content-Type in the request header should be "application/x-www-form-urlencoded". I used REST Client in Firefox to test the request and it works, but in the above code the request is not being made at all. What is the error in my code ?

Thank You

回答1:

This is being stopped as a XSS attack. Even though they are on the same domain, the sub-domains are different, and that's enough. For more information, see Are AJAX calls to a sub-domain considered Cross Site Scripting?.

To correct this, you could simply make the AJAX hit your local controller, and make the request using ruby, which would not be limited by said restriction.



回答2:

You can also set this settings:

jQuery.support.cors = true;

This enables you to do cross domain calls with jQuery. It's probably not the best solution, since you are adding a vulnerability by using the following request header: Access-Control-Allow-Origin.