DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Christian Walter
Christian Walter

Posted on

React - axios Post response has no Cookie

Hello everyone,
I am currently working with React for the frontend and Symfony PHP framework for the backend. Now I am trying to log in to the backend via React with a post request. This all works very well so far. I get a 204 code and I am then logged in. About Postman, with the same request, I get as a response a cookie for the session-based authentication. About PHP and cURL I got in the response from the backend a cookie

Postman response

The response by cURL looks like this:

{'Date': 'Sat, 08 Oct 2022 10:14:45 GMT', 'Server': 'Apache', 'Cache-Control': 'max-age=0, must-revalidate, private', 'Link': '<http://127.0.0.1:8000/api/docs.jsonld>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"', 'X-Debug-Token': 'cca986', 'X-Debug-Token-Link': 'http://127.0.0.1:8000/_profiler/cca986', 'X-Robots-Tag': 'noindex', 'Expires': 'Sat, 08 Oct 2022 10:14:45 GMT', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Set-Cookie': 'PHPSESSID=2606e8ab1c7ded0d30bb61890f4a6ea0; path=/; secure; httponly; samesite=lax', 'Location': '/api/users/11', 'Keep-Alive': 'timeout=5, max=100', 'Connection': 'Keep-Alive'}
Enter fullscreen mode Exit fullscreen mode

PHP Code:

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => 'http://127.0.0.1:8000/login',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS =>'{
        "email": "webmaster",
        "password": "123456"
    }',
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
    ),
));
$response = curl_exec($curl);
Enter fullscreen mode Exit fullscreen mode

As soon as I don't use in the cURL variant the option "CURLOPT_HEADER => true," the cookie and the detailed response are no longer displayed.

Now I have tried all options to get the cookie also in React and Axios in the header, unfortunately it is not possible for me even remotely somehow to get a cookie or other response from the backend. Here is the code I am currently using.

let data = {email:"webmaster", password:"123456"}
let headers = {
  headers: {'Content-Type': 'application/json'}
};


const axiosConfig = {
  headers: {
    'content-Type': 'application/json',
    "Accept": "/",
    "Cache-Control": "no-cache",
    "Access-Control-Allow-Origin": "*",
    // "Cookie": document.cookie
  },
  credentials: "same-origin"
};
axios.defaults.withCredentials = true;
const res = await axios.post('http://127.0.0.1:8000/login', data, axiosConfig)
    .catch(response =>{
      console.log(response.getAll());
})
Enter fullscreen mode Exit fullscreen mode

React response after Post request

Unfortunately I don't know if I forgot anything in the post request or if Axios is not the best for such a request.

I am just surprised that in Postman and via PHP there are no problems to get a cookie. Unfortunately, I have only recently started working with ReactJS and have very little experience in this area.

On the weekend I tried it also with python and there were also no problem. So I think it is a problem of my ReactJS code.

Thanks a lot for your help!

Best, Christian

Top comments (7)

Collapse
 
thematchless profile image
Matthias Meyer

I am not sure if i understand your problem correct but why are you using a catch for your axios.post method and not a then?

I would create my request in a pattern like this:

const res = await axios.post('http://127.0.0.1:8000/login', data, axiosConfig)
    .then((response) => {
      // will be called if the request was successful
      console.log(response)
    }).catch((error) => {
      // will be called if there was an error
      console.error(error);
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
itsclx profile image
Christian Walter

Thank you for your idea. Unfortunately I don't get a cookie back with the response. Normally, as with the other languages, there should be a cookie in the response... That's actually my problem.

Collapse
 
itsclx profile image
Christian Walter

I am still very new with the programming language react and therefore thought it would be a good solution for a post request.
I will try your solution directly.

Collapse
 
thematchless profile image
Matthias Meyer • Edited on

There are some more things to consider:

HTTP only secure cookies cannot be accessed in JavaScript ❗️ In the Screenshot of your Postman request i can see that the PHPSESSID is set to a HTTP only Cookie. Therefore, you do not have access to the cookies via Javascript.

But if your user credentials are correct and the server responds with your "HTTP only" cookie, the cookie will be automatically included in all requests as long as the same-site policy is not violated.

I would be the best option to trace the login request in your debug tools for your browser. Go to the network tab and select your login request. If your credentials are valid your should see that the server responds with your cookies even if is a HTTP only cookie.

Thread Thread
 
itsclx profile image
Christian Walter

Thank you for the information.
I did not know that until now.
Then I will try it via same-site cookie.

Thread Thread
 
itsclx profile image
Christian Walter

@thematchless I have one more questions maybe you can answer this also.
In Postman I get in the header response with a Location. But in JS there are only those two attributes you can see in the screenshot.
Is there a way to get the Location attribute aswell?

Thread Thread
 
itsclx profile image
Christian Walter

Sorry,
got it! It was a settings issue with nelmio cors. Hat to add: expose_headers: ['Location']

Best,
Christian

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.