Experiencing difficulties when attempting to send a cookie to the server

Why is the vue+axios frontend not sending cookies to my php server in the request header?

I am currently in the process of migrating an old project to a new server. After making some optimizations to the project architecture, everything worked perfectly fine in my local docker environment. However, upon moving it to the production environment, I encountered some issues. The project has two separate domains for each side - admin.example.com for the frontend and serve.example.com for the backend. I have manually set the cookie_path to / and cookie_domain to .example.com in the server code. Even though the frontend receives an expected set-cookie in the backend response header, it fails to send the cookie to the backend in subsequent requests. As a result, the login status cannot be maintained.

const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 15000,
  withCredentials: true,
  transformRequest: [function (data) {
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }],
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
// PHP code
session_set_cookie_params(
            C('COOKIE_EXPIRE'),
            C('COOKIE_PATH'),
            C('COOKIE_DOMAIN'),
            C('COOKIE_SECURE'),
            C('COOKIE_HTTPONLY')
);
session_name(C('SESSION_NAME'));

// PHP config

'SESSION_NAME'          => 'xxxxx',

'COOKIE_EXPIRE'         =>  3600,
'COOKIE_DOMAIN'         =>  '.example.com',
'COOKIE_PATH'           =>  '/',
'COOKIE_PREFIX'         =>  '',
'COOKIE_SECURE'         =>  false,
'COOKIE_HTTPONLY'       =>  false,

The response header appears as follows:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:DNT,X-Token,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding
Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE
Access-Control-Allow-Origin:http://admin.example.com
Set-Cookie:beb257200166c10f69c4667d621785f7=9m7e9lonmjtvh06fn3fi0nul71; expires=Thu, 08-Aug-2019 13:29:29 GMT; Max-Age=3600; path=/; domain=.example.com
X-Content-Type-Options:nosniff

Expected Outcome: The browser should send the cookie in each request in order to maintain the login status.

Actual Outcome: The cookie is not being sent, resulting in the browser receiving a different session key with each request.

Answer №1

After realizing a mistake made last night, I discovered that the browser was not sending cookies to the backend server due to my friend deploying his frontend code on our project's server. To fix this issue, you only need to take two steps:

  1. Add "Access-Control-Allow-Credentials:true" and "Access-Control-Allow-Origin:frontend_domain" to your backend response header. Remember that * cannot be used as the value for Access-Control-Allow-Origin in this situation.

  2. Update your axios configuration by setting "withCredentials:true". By default, this key is set to false, so adjusting it will allow axios to send cookies with cors requests. For more information, visit this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the process of incorporating hyperlinks into individual table entries with the PrimeVue DataTable component

The default setup of PrimeVue library does not support this feature. Here is how the Table currently appears: example image. Displayed below is an array containing product information: products: [ {brand: "Volkswagen", year: 2012, color: ...

Laravel 5 is known for experiencing a frustrating "This site can't be reached" error message when attempting to download a file

I am experiencing an issue with my Laravel 5.2 and PHP7 setup on my hosting server. Everything seems to be working fine, except for the links that are supposed to generate and download xlsx files using Laravel Excel. Whenever I click on these links, I enco ...

Customize the data attributes of Vuetify v-select options for added functionality

I am currently utilizing a v-autocomplete component to display items in a selector. Given that v-autocomplete is essentially just an enhanced version of v-select, I believe a solution for v-select would be applicable for v-autocomplete as well. Within my ...

Is there a way to choose a specific area within an image, blur it, and add a watermark to it?

I've been searching extensively, but I just can't seem to find a solution. I discovered a watermarked script, but what I really need is a script that allows me to select a specific region from an image and blur it. Currently, I am working with a ...

Is there a way to transfer a value set from one tpl file to another tpl file in cscart using smarty template engine?

I am trying to retrieve the value of a variable set using an input tag from one tpl file. Here is the input tag in A.tpl file: <input type="checkbox" class="checkbox" name="payment_data[processor_params][enable_addbillcard]" id="optional_enable_addbil ...

Receiving JSON output twice

I am currently working with CodeIgniter and facing an issue with my form fields, which are Employee_name, fromDate, and endDate. I am using AJAX to send this data without sharing the actual code. The problem arises when retrieving and displaying records fr ...

Importing dynamic components in Vue with Vite is a seamless

Currently in the process of migrating an existing Laravel inertia project from Mix to Vite. Followed all the steps in the migration guide and everything is functioning properly except for one issue. I have a component that receives a prop containing an a ...

initiate changes to the application's style from a component nested within the app

I'm looking to update the background color of the entire page, including the app-nav-bar, when I'm inside a child component. When I navigate away from that component, I want the default style to be restored. Any suggestions on how to achieve this ...

Restrict the amount of displayed information in Vue

I'm having trouble creating a Vue button that limits the display of items fetched from an API. The goal is to only show 3 out of 10 questions initially, and when the "showmore" button is clicked, another set of 3 should be displayed, and so on. Howeve ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Is it possible to utilize IterateAggregate or Iterator within a foreach loop in PHP?

I am just starting out with PHP and relying on php.net for my learning. I came across a note on this page(http://php.net/manual/en/class.traversable.php) that states: Internal (built-in) classes that implement this interface can be used in a foreach const ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

Merging WordPress login with an established user database

I am managing a database that contains a user table with the following fields: id name email password status Users log in using their email and password. I have recently set up a blog at mysite.com/news. My goal is to have new user registrations aut ...

Inquiry about Codeigniter URL structure

How can I create user-specific URLs, like www.domain.com/username I understand that a route system may be necessary for this. While I have experience using it for other URL requests, I am unsure if I need to consider my other controller classes when dy ...

The main content will be displayed on the sub-routes of the child

I'm feeling uncertain about the routes for children. For example, I have an 'About' route with 'me' as a sub-route: { path: '/about', name: 'About', component: About, children: [ { ...

Fetch external navigation and refresh hyperlinks

After spending an hour searching on Google without finding a solution to my problem, I decided to reach out here for help. Currently, I have a site hosted on a CMS platform and recently created a WordPress blog on a subdomain on a new server. Unfortunatel ...

Struggling to properly send props to the child component in Vue 3

Is there a way to pass data from the request through axios in the root component to the child using Vue? Currently, only the "title" field is displayed correctly, but I also need to output the "body". Note: This is my first time working with Vue and I&apo ...

What is the specific hook in WordPress that is utilized for creating a customized login URL?

Looking to create a WordPress plugin that allows for custom URLs (besides wp-admin.php and wp-login.php). Interested in finding out the necessary hook to achieve this. Thanks! ...

Tips on identifying the source of a segmentation fault in a script executed by a cron job

I currently have a cron job set to run once per day: 0 20 * * * /usr/bin/wget --timeout=10800 -O /home/File.txt http://www.site.com/script.php Everything was running smoothly until recently when I discovered that the script suddenly stops functioning. A ...

Navigating URLs to Single Page Application Routing in Vue.js

I'm new to using vue-router and I'm curious if there's a way to manage redirection in Vue or if there are alternative methods in a node.js environment. For instance, when someone tries to access my site by typing the URL example.com/contac ...