【发布时间】:2017-12-07 04:37:06
【问题描述】:
一段时间以来,我一直在尝试从 php 中检索 cookie。
从php我有这个方法:
public function created()
{
$datetime = date_create()->format('Y-m-d H:i:s');
$json =file_get_contents('php://input');
var_dump($json);
$decoded = json_decode($json, true);
$cookie="";
$obj=new \stdClass();
if($decoded['cookie']==""){
$cookie=$random = rand(1,1000);
setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost" );
}
else{
$cookie=$decoded['cookie'];
}
$user=[
'name'=>$decoded['name'],
'surname'=>$decoded['surname'],
'email'=>$decoded['email'],
'review'=>$decoded['review'],
'time'=>$datetime,
'cookie'=>$cookie,
];
$obj->cookie=$cookie;
DatabaseModel::newuser($user);
//return response()->json($cookie);
}
如果不存在 cookie,它会创建 cookie,我会在响应标头中看到它。 (暂时不要关注我是如何创建cookie的,我现在的rand()函数不是正确的方法,它只是为了测试)
在我有棱角的一面:
function PostReview(JSONObject) {
if (JSONObject != null) {
debugger;
$http({
url: 'http://localhost:8000/creation',
method: "POST",
data: JSONObject,
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
"Accept": "application/json"
},
})
.then(function (data) {
console.log(data.headers('Set-cookie'));
}, function (data) {
console.log(data.headers('Set-cookie'));
});
}
}
我想发布我的 JSON 对象并接收带有响应的 cookie。但是我很困惑。我尝试使用 .success() 但它已被弃用,所以我使用 .then() ,但随后我打印 console.log(data.headers('Set-cookie')); 我得到空结果。有没有人遇到过类似的问题?
我也试过了:
.then(function (data, status, headers, config) {
console.log(headers('Set-cookie'));
}, function (data, status, headers, config) {
console.log(headers('Set-cookie'));
});
和:
.then(function(response) {
if (response.data == 'ok') {
$cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
// below put,put,putObject Cookies value is valid for Angular version >= 1.4
var $cookie= $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN'));
console.log($cookie);
debugger;
}
});
但他们都没有工作。会是什么问题?
我的客户端:
function PostReview(JSONObject) {
if (JSONObject != null) {
debugger;
$http({
url: 'http://localhost:8000/creation',
method: "POST",
data: JSONObject,
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
"Accept": "application/json"
}
})
}
}
在我的控制器中:
$scope.Cookie = $cookies.get('cookie');
$scope.$watch('Cookie', function() {
$scope.Cookie = $cookies.get('cookie');
});
跨域 cookie 怎么样?
【问题讨论】:
-
要获取您定义的 cookie,只需在您的控制器中注入
$cookies,然后使用$cookies.get("cookie");...您需要准确发布您的客户端的外观和位置重新使用$cookies.get("cookie");,这样会更容易帮助你 -
@ElmerDantas 我更新了我的答案,我尝试在各个地方添加
$cookies.get("cookie");,但我想我应该看看它。但似乎没有任何效果 -
你能不能在控制器上放一个
console.log来打印$cookies.get("cookie");发出请求然后刷新页面?可能你会看到它的价值。恐怕您无法以尝试的方式访问该值 -
刚才我注意到您使用的不是同一个域,,,这是为什么呢?
-
因为我的 php 服务器在 localhost:8000 中,而我的前端在 localhost/