Home > Backend Development > PHP Tutorial > javascript - ajax跨域获取session的问题

javascript - ajax跨域获取session的问题

WBOY
Release: 2016-06-06 20:06:23
Original
1344 people have browsed it

最近在研究angularjs,想搞个前后端分离,结果发现ajax跨域请求时session丢失了?
前端www.book.com
后端api.book.com
后端设置了

<code>ini_set('session.cookie_domain', ".book.com");
header("Access-Control-Allow-Origin:*");</code>
Copy after login
Copy after login

所以现在单纯的前端发送ajax请求到后端返回数据是可以获得到的,
但前端发送请求到后端,后端打印session为null。

<code><pre class="brush:php;toolbar:false">array(0) {
}
Copy after login
Copy after login

我做了实验,前端放了个php,test.php

<code><?php ini_set('session.cookie_domain', ".book.com");
session_start();
var_dump($_SESSION);</code></code>
Copy after login
Copy after login

使用www.book.com/test.php访问,结果是有的

<code>array(2) { ["d2d977c58444271d9c780187e93f80e5login"]=> array(2) { ["verify_code"]=> string(32) "748247cb9c625028d55e6a6bb90f7dc8" ["verify_time"]=> int(1464936279) } ["d2d977c58444271d9c780187e93f80e5resigiter"]=> array(2) { ["verify_code"]=> string(32) "2cfddfe2efaa2a0d78cd20c367df52f7" ["verify_time"]=> int(1464930066) } }</code>
Copy after login
Copy after login

也就是说我在跨二级域名直接访问,是成功能获取到session的,但在www.book.com的页面中ajax到api.book.com就拿不到了?

回复内容:

最近在研究angularjs,想搞个前后端分离,结果发现ajax跨域请求时session丢失了?
前端www.book.com
后端api.book.com
后端设置了

<code>ini_set('session.cookie_domain', ".book.com");
header("Access-Control-Allow-Origin:*");</code>
Copy after login
Copy after login

所以现在单纯的前端发送ajax请求到后端返回数据是可以获得到的,
但前端发送请求到后端,后端打印session为null。

<code><pre class="brush:php;toolbar:false">array(0) {
}
Copy after login
Copy after login

我做了实验,前端放了个php,test.php

<code><?php ini_set('session.cookie_domain', ".book.com");
session_start();
var_dump($_SESSION);</code></code>
Copy after login
Copy after login

使用www.book.com/test.php访问,结果是有的

<code>array(2) { ["d2d977c58444271d9c780187e93f80e5login"]=> array(2) { ["verify_code"]=> string(32) "748247cb9c625028d55e6a6bb90f7dc8" ["verify_time"]=> int(1464936279) } ["d2d977c58444271d9c780187e93f80e5resigiter"]=> array(2) { ["verify_code"]=> string(32) "2cfddfe2efaa2a0d78cd20c367df52f7" ["verify_time"]=> int(1464930066) } }</code>
Copy after login
Copy after login

也就是说我在跨二级域名直接访问,是成功能获取到session的,但在www.book.com的页面中ajax到api.book.com就拿不到了?

需要在CORS的头里允许cookie,并且在发起ajax的时候设置withCredentials:true

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template