Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XDomainRequest #4

Open
RubyLouvre opened this issue Oct 10, 2016 · 0 comments
Open

XDomainRequest #4

RubyLouvre opened this issue Oct 10, 2016 · 0 comments

Comments

@RubyLouvre
Copy link
Owner

微软官方文档

想要成功地使用XDomainRequest对象进行跨域,关键点在于要在server端设置res.header('Access-Control-Allow-Origin','*')

首先,在阿里云4服务器中,新建一个xdr.html:

<!DOCTYPE html>
<html>
<body>
  <h2>XDomainRequest</h2>
  <input type="text" id="tbURL" value="http://120.27.45.36:3003/error_reciver" style="width: 300px"><br>
  <input type="text" id="tbTO" value="10000"><br>
  <input type="button" onclick="mytest()" value="Get">&nbsp;&nbsp;&nbsp;
    <input type="button" onclick="stopdata()" value="Stop">&nbsp;&nbsp;&nbsp;
    <input type="button" onclick="readdata()" value="Read">
  <br>
  <div id="dResponse"></div>
  <script>
    var xdr;
    function readdata(){
      var dRes = document.getElementById('dResponse');
      dRes.innerText = xdr.responseText;
      alert("Content-type: " + xdr.contentType);
      alert("Length: " + xdr.responseText.length);
    }

    function err(){
      alert("XDR onerror");
    }

    function timeo(){
      alert("XDR ontimeout");
    }

    function loadd(){
      alert("XDR onload");
      alert("Got: " + xdr.responseText);
    }

    function progres(){
      alert("XDR onprogress");
      alert("Got: " + xdr.responseText);
    }

    function stopdata(){
      xdr.abort();
    }

    function mytest() {
      var url = document.getElementById('tbURL');
      var timeout = document.getElementById('tbTO');
      if (window.XDomainRequest) {
        xdr = new XDomainRequest();
        if (xdr) {
          xdr.onerror = err;
          xdr.ontimeout = timeo;
          xdr.onprogress = progres;
          xdr.onload = loadd;
          xdr.timeout = tbTO.value;
          xdr.open("get", tbURL.value);
          xdr.send();
        } else {
          alert("Failed to create");
        }
      } else {
        alert("XDR doesn't exist");
      }
    }
  </script>
</body>
</html>

然后在阿里云5服务器中,新建一个xdr.js:

'use strict';
const express = require('express');
const useragent = require('useragent');
const mysql = require('mysql');
const app = express();
// 使用路由
const router = express.Router();
app.use('/test_xdr', router);

router.get('/', (req, res) => {
  res.header('Access-Control-Allow-Origin','*'); // 这句是重中之重!!!!!
  res.end('hello XDomainRequest');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant