We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Impossible to set cookie in Micro Application Ajax API

Hi everybody \0/

I'm using Phalcon to create micro application (API Rest/JSON) :

<?php
use Phalcon\Http\Response;

$app = new Micro($di);

$app->post('/url', function() use ($app){
    ...
    $params = $app->request->get();

    $response = new Response();

    setcookie('foo', 'bar');

    $response->setStatusCode(200, "OK");
    $response->send();

});

this address is called by ajax request

HTTP Ajax Response :

HTTP/1.1 200 OK
Server: nginx
Date: Fri, 11 Dec 2015 14:09:05 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: foo=bar; expires=Sun, 10-Jan-2016 14:09:04 GMT; Max-Age=2592000
access-control-allow-origin: *
Content-Encoding: gzip

But $_COOKIE stay empty...

Someone can help me to know why ?

Thank you.



5.9k
edited Dec '15

How to reproduce :

PHP Example:

<?php
$app->get('/url', function() use ($app){
    /*
     * Get params request (POST)
     */
    $params = $app->request->get();

    if(isset($_COOKIE['foo'])) {
        $res = "hello world!";
    } else {
        setcookie('foo', 'bar');
        $res = "heho";
    }

    $response = new Response();
    $response->setStatusCode(200, "OK");
    $response->setContent("<html><body>$res</body></html>");
    $response->send();
});

Javascript Example:

$.ajax({
  url:'https://external-site.dev/url',
  success: function(data){
    console.log(data);
  }
});

Expected:

first call : Heho second call : Hello world!

Actual result:

first call : Heho second call : Heho

Thank you

AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script.



5.9k

It's working with

xhrFields: {
      withCredentials: true
  },

In Ajax query options but with error message :

Blocage d'une requête multi-origines (Cross-Origin Request) : la politique « Same Origin » ne permet pas de consulter la ressource distante située sur https://external-domain.dev/api/url. Raison : l'en-tête CORS « Access-Control-Allow-Origin » ne correspond pas à « * ».

So now, it's a problem with Nginx configuration... ?



145.0k
Accepted
answer
edited Dec '15

Kind of, you have to add to headers like this:

add_header 'Access-Control-Allow-Origin' 'website';
add_header 'Access-Control-Allow-Credentials' 'true';