前端(包含cocosCreator)开发环节调取后端接口时跨域,解决办法之反向代理

/** eslint-disable */
var http = require('http'),
  httpProxy = require('http-proxy'),
  HttpProxyRules = require('http-proxy-rules');

// Set up proxy rules instance
var port = 9090
var proxyRules = new HttpProxyRules({
  rules: {
    '/api/(.*)': 'https://baidu.com/$1', // 测试环境游戏服务
  },
  default: 'https://baidu.com', // default target
});

// Create reverse proxy instance
var proxy = httpProxy.createProxy({ autoRewrite: true, changeOrigin: true });

// Create http server that leverages reverse proxy instance
// and proxy rules to proxy requests to different targets
http
  .createServer(function (req, res) {
    // a match method is exposed on the proxy rules instance
    // to test a request to see if it matches against one of the specified rules
    var target = proxyRules.match(req);
    console.info({ target });
    if (target) {
      // 设置跨域头
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:7456');
      res.setHeader('Access-Control-Allow-Credentials', 'true');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, App-Info, X-Device, Session');
      // 检查请求是否为预检请求
      if (req.method === 'OPTIONS') {
        // 返回 HTTP OK 状态码(200)以满足预检请求的要求
        res.writeHead(200);
        res.end();
        return;
      }
      return proxy.web(req, res, {
        target: target,
      });
    }


    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('The request url and path did not match any of the listed rules!');
  })
  .listen(port);

console.info('======proxy on localhost: ' +port + '======');
console.info('===proxy table===');
console.info({
  rules: {
    '/api/(.*)': 'https://baidu.com/$1', // 测试环境游戏服务
  },
  default: 'https://baidu.com', // default target
});

用后端给的接口前缀来代替代码中的 ::::::     https://baidu.com 
即可监听本地的http://localhost:7456/   中带api关键字的访问,反向代理到后端服务器

原理是:

  1.    前端和后端不在同一个服务器域名下,会造成跨域阻拦。
  2.   后端和后端的访问不管是不是同源环境,是不是一个域名下,都不会有跨域阻拦。
  3.   node.js起一个简单的后端服务,将前端对后端的跨域访问,先通过node服务和本地前端都是本地的同源关系正常访问node服务,node反向代理到跨域的后端服务上成服务器之间的访问。

     解决办法常用的就是如上,还可以找后端将服务器改为不阻止跨域,后端没安全感,一般不干。
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值