前端代码(cocos)部署在nginx,前端功能里访问第三方url跨域问题解决

前端代码(cocos)部署在nginx,前端功能里访问第三方url跨域问题解决。

(1)前情交代:前端代码打包后部署在nginx使用浏览器访问,其中一功能访问第三方url报错跨域,这个第三方url是别人的,而且从安全考虑,根本不可能改啊😄。

(2)问题解决描述:在nginx配置中使用反向代理把请求转发到第三方url。

先上nginx配置:

server {
    # ... 其他配置
    location ~ [^/]\.php(/|$) {
        # comment try_files $uri =404; to enable pathinfo
        try_files $uri =404;
        fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
        #include pathinfo.conf;
    }

    # ... 其他location

    # 本location使用 = 匹配,优先级高,匹配上就不再匹配其他location,避免在php中对请求处理
    # 而缺失路由报错。
    location = /faq/821550.html {
        proxy_pass    https://www.php.cn/;
        add_header      Access-Control-Allow-Origin *;
        add_header      Access-Control-Allow-Methods "GET,POST,OPTIONS,PUT,DELETE";
        add_header      Access-Control-Allow-Credentials true;
        add_header      Access-Control-Allow-Headers "Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token";
        if ($request_method = 'OPTIONS') {
            return 200;
        }
    }
}

前端请求代码示例:

fetchText: function (evt) {
    /*
      本来请求信息地址是这个,但是直接POST该地址,跨域。
      所以使用我们自己的域名和端口,把请求做一个转发
      var url = 'https://www.php.cn/faq/821550.html'; 
    */
	var url = 'http://192.168.2.221:8002/faq/821550.html';
	var httpReq = new XMLHttpRequest();
	httpReq.open('POST', url, true)
	httpReq.setRequestHeader('Content-type', 'application/json');
	var obj = {'username': 'waki'}
	httpReq.send(JSON.stringify(obj));
	httpReq.onreadystatechange = function() {
		console.log('readyState => ', httpReq.readyState)
		console.log('responseText => ', httpReq.responseText)
	}
}

 抛砖引玉,对nginx不是很熟悉,有更巧的办法一起讨论。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值