如何解决 XMLHttpRequest 跨域请求的问题

在Web开发中,跨域请求是一个常见的问题,解决的办法有多种,这里推荐一个轻量级的针对 XMLHttpRequest 请求的跨域解决方法。

闲话不说,直接看code:

客户端发起一个跨域的请求:

anHttpRequest = new XMLHttpRequest();


anHttpRequest.onreadystatechange = function() {
  if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200){

    // handle your response here when it's successful.
    aCallback(anHttpRequest.responseText);

}

anHttpRequest.open( "GET", "http://anotherdomain.com/testApi", true );
anHttpRequest.send( null );

服务器端,我们要做的就是把这个origin设置成被允许的,代码如下:

简单的方法如下:

    Response.AddHeader("Access-Control-Allow-Origin", "http://origindomain:801");   
    Response.Write("跨域测试成功!");   

我因为服务器端是用NodeJs写的,用了express 中间件,那实际的代码类似于这样的:

// Module dependencies.
var application_root = __dirname,
  express = require( 'express' );

//Create server
var app = express();

app.all('*', function(req, res, next){
  if (!req.get('Origin'))

    return next();


  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', 'http://origindomain:801');
  next();
});

看起来是不是很容易?

原文地址:https://www.cnblogs.com/johnonsoftware/p/3995665.html