Tools
首页
画图
音乐
采集
记事
博客
实验室
登录
lypeng
146
文章
11
分类
46
记事
分类
生活-[23]
Linux-[24]
前端-[9]
数据库-[16]
PHP-[31]
git-[7]
其他-[6]
python-[20]
算法-[4]
React-Native-[4]
中草药-[2]
广告位1
广告位2
首页
/ PHP
返回列表
解决No Access-Control-Allow-Origin跨域问题
阅读:904
发布:2018-01-10
作者:lypeng
# 2018-05-21更新 今天设置了header信息,但是访问依旧报:No 'Access-Control-Allow-Origin' header,都看到发送了两次请求,一次options,一次post,很奇怪,为什么呢? 一开始我忽略了一个问题: ``` Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0 Warning: Cannot modify header information - headers already sent in Unknown on line 0 Warning: Cannot modify header information - headers already sent in /server/index.php on line 3 ``` 警告:不能修改header信息,因为header已经发送在第0行 我一直不知道这个第0行是哪儿?我也没有使用`$HTTP_RAW_POST_DATA`这个变量。既然是警告,我没在意,到处瞎改测试;最后实在没办法,修改了php.ini,解决这个问题后,好了!就这样好了????????? 原因:因为我的header没设置成功~header跨域信息设置失败, 但有一点,header失败了,为什么会有两次请求? 难道不是第一次options请求预检通过后,才发送第二次的post请求么?如果options失败,直接中断么?不理解~~~ 学到知识点: 1. `header('Access-Control-Max-Age:180'); //options请求成功后,180秒内不会再次发送options` 2. headers_sent检测header发送信息 ``` if (!headers_sent($file, $line)){ header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:POST,OPTIONS'); header('Access-Control-Allow-Headers:x-requested-with,content-type'); header('Access-Control-Max-Age:180'); header('content-type:application/json;charset=utf8'); }else{ echo "Headers sent in $file on line $line"; exit; } ``` ----------------- # 什么是跨域? 使用js获取数据时,涉及到的两个url只要协议、域名、端口有任何一个不同,都被当作是不同的域,相互访问就会有跨域问题。 > 例如客户端的域名是 www.a.com, 而请求的域名是 www.b.com 如果直接使用ajax访问,会有以下错误 No 'Access-Control-Allow-Origin' header is present on the requested resource. www.a.com html内容如下 ```html
Page Title
``` # 如何解决跨域? ## 方法一 修改www.b.com index.php内容,增加四行header ```php ``` ## 方法二 修改nginx.conf配置文件 在服务器端的nginx.conf中配置增加配置 ``` http { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; } ``` ## 方法三 nginx反向代理 例如,www.acom 想请求www.b.com/api/index.php; ```javascript var url = 'www.b.com/api/index.php'; $.ajax({ type: "GET", url:url, success: function(res){..}, .... }) ``` 变成访问本地域名地址 ```javascript var url = 'http://www.a.com/api/index.php'; $.ajax({ type: "GET", url:url, success: function(res){..}, .... }) ``` 通过nginx中增加location反向代理到服务器端 ``` location ^~/api/{ rewrite ^/api/(.*)$ /$1 break; proxy_pass http://www.b.com/api/; } ``` 原文章地址:[http://www.nginx.cn/4592.html](http://www.nginx.cn/4592.html?_blank "http://www.nginx.cn/4592.html")
------本文结束
感谢阅读------
上一篇:
thinkphp自带的消息队列think-queue学习测试
下一篇:
【转】php安装扩展的几种方法