Can I use XMLHttpRequest on a different port from

2019-01-26 07:31发布

I have website that use XMLHttpRequest (jQuery, actually). I also have another site running on the same server, which serves a script file that makes XHR requests back to THAT site, ie.

http://mysite:50000/index.html includes

<script src="http://mysite:9000/otherscript.js"></script>

and http://mysite:9000/otherscript.js includes

$.ajax({
    url: 'http://mysite:9000/ajax/stuff'
});

The problem is - this doesn't work. The AJAX requests from the loaded script simply fail with no error message. From what I've been able to find this is the old same origin policy. Given that I control both sites, is there anything I can do to make this work? The "document.domain" trick doesn't seem to do a thing for XMLHttpRequest.

3条回答
Emotional °昔
2楼-- · 2019-01-26 07:50

Nope- can't do this with XHR. Same-domain policy is very restrictive there- same host, same port, same protocol. Sorry! You'll have to resort to other tricks (iframes, title manipulation, etc) to get it to work.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-26 07:52

I just solved a similar issue with a PHP service I'm currently playing around with (not sure how relevant a PHP solution is to this directly, but...) by making a single line proxy PHP page, SimpleProxy.php:

<?php
echo file_get_contents('http://localhost:4567');
?>

And in my XMLHttpRequest I use 'SimpleProxy.php' in place of 'http://localhost:4567', which effectively puts the request on the same domain as my .js code.

查看更多
看我几分像从前
4楼-- · 2019-01-26 07:57

You can do this by adding Access-Control-Allow-Origin header.

If you are using PHP

header("Access-Control-Allow-Origin: http://example.com");

or in Node.js

response.writeHead(200, {'Access-Control-Allow-Origin':' http://example.com'});

This should do the trick for you. It always works for me.

查看更多
登录 后发表回答