php+nginx配置通过服务端配置解决ajax请求跨域问题(本人亲测)

服务端解决前端JS Ajax请求的跨域问题:
 

方法1: PHP代码上添加如下代码(*星号不能有空格,,加在最底层代码)

header("Access-Control-Allow-Origin:*");

    /** 例:用于H5充值页面查询用户信息
     *  /api/hpay/getUserInfo?username=18857xxxx25
     */
    function getUserInfo(){
        header("Access-Control-Allow-Origin:*");  //一行代码搞定Ajax跨域问题
        $mobile = input('username','','trim');
        if(empty($mobile)){
            $this->toJson('请输入手机号.',0,[]);
        }
        if((strlen($mobile)!=11)){
            $this->toJson('你输入的手机号有误.',0,[]);
        }
        $find = M('user')->field('user_name,u_pic,nick_name')->where(['mobile'=>$mobile])->find();

        if(!$find){
            $this->toJson('手机号有误或不存在.');
        }
        $this->toJson('查询成功.',1,$find);
    }

方法2: nginx 配置允许跨域请求

add_header Access-Control-Allow-Origin *;
#add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
#add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";   

如果还是有JS报错,页面跳转报错,例如: This request has been blocked; the content must be served over HTTPS
 
报错原因:
http、https混合导致的

网站用的是 https 要跳转到 http 请求,被阻止了。

解决方法:
1.页面中都是用 https ,或者都使用 http

2.如果都已经配置好了https,则可以在 <head> 的meta标签中添加以下代码

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"/>

意思是自动将http的不安全请求全部升级为https的请求
 

扫描二维码关注公众号,回复: 14998014 查看本文章


推荐使用方法,经过本人测试,各个浏览器都OK的。。。

猜你喜欢

转载自blog.csdn.net/happyzhlb/article/details/123552368
今日推荐