Cross-site AJAX requests

2019-01-03 15:51发布

I need to make an AJAX request from a website to a REST web service hosted in another domain.

Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.

The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.

Here is the JavaScript code that makes the asynchronous call:

var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);

How can I have this work in other browsers beside Internet Explorer?

8条回答
Juvenile、少年°
2楼-- · 2019-01-03 16:47

Another option would be to setup a CNAME record on your own domain to "Mask" the remote domain hostname.

查看更多
等我变得足够好
3楼-- · 2019-01-03 16:52

This can also be done using a webserver setup localy that calls curl with the correct arguments and returns the curl output.

app.rb

require 'sinatra'
require 'curb'

set :views,lambda {"views/"+self.name.to_s.downcase.sub("controller","")}
set :haml, :layout => :'../layout', :format => :html5, :escape_html=>true
disable :raise_errors

get '/data/:brand' do
  data_link =  "https://externalsite.com/#{params[:brand]}"
  c = Curl::Easy.perform(data_link)
  c.body_str
end

Sending an ajax request to localhost:4567/data/something will return the result from externalsite.com/something.

查看更多
登录 后发表回答