Can I use XMLHttpRequest on a different port from a script file loaded from that port?

后端 未结 3 1124
故里飘歌
故里飘歌 2020-12-19 01:52

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 TH

相关标签:
3条回答
  • 2020-12-19 02:08

    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.

    0 讨论(0)
  • 2020-12-19 02:28

    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.

    0 讨论(0)
  • 2020-12-19 02:30

    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.

    0 讨论(0)
提交回复
热议问题