如何解决 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值