Retrieve and save the cookie provided in the Set-Cookie header of an AJAX POST reply

Here is a straightforward jQuery AJAX POST code snippet:

$.ajax({
    type: "POST",
    url: AppConstants.URLs.PROXY,
    data: message,
    xhrFields: {
        withCredentials: true
    },
    success: function(data, status, xhr) {
        console.log("Cookie: " + xhr.getResponseHeader("Set-Cookie"));
    }
});

I am looking to retrieve the cookie and store it using cookies-js.

However, as stated in the documentation at http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method:

  1. Return all response headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.

Despite seeing "Set-Cookie" in the Response headers in Chrome's Network tool, I have confirmed the presence of the "Set-Cookie" header using curl as well.

Could you please guide me on how to save the cookie in my front-end application? Additionally, note that my application operates solely on https.

If more information is needed, I'd be happy to provide it upon request.

Answer ā„–1

Accessing cookie data in JavaScript is restricted by the API.

What steps should I take to store a cookie in my frontend application?

To save a cookie, simply include the Set-Cookie header in your server-side response. The browser will handle the rest.

For developers, you can utilize "Developer Tools" to view the cookie values.

The same cookie will persist in subsequent requests to the domain until it expires.

Answer ā„–2

Due to security reasons, the browser is unable to grant access to third-party cookies received from ajax requests. However, it automatically handles them for you!

To make this function properly, follow these steps:

1) Log in through the ajax request that will return cookies:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) Enable

xhrFields: { withCredentials: true }
in subsequent ajax requests to utilize the credentials stored by the browser

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

Even though these cookies are not visible in the headers or document.cookie, the browser manages them on your behalf.

Check out my response here: How to get a cookie from an AJAX response?

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

Sending File from React to Express Causes 404 Error

My current project setup involves a React application housed in a client folder and an Express server located in the root directory. Within the React app, there are functionalities for selecting files and submitting them. I aim to transfer these files from ...

Enter the Kannada language into the HTML text box or input field

My html form consists of about 15 - 20 input and textarea fields. As a user, how can I enter information in Kannda or any other local language? https://i.stack.imgur.com/60PVT.png ...

All the routes stored in the Express app's (express-promise-router) directory

Currently in my backend application, I am utilizing express-promise-router to handle my routes effectively. Here is an example code snippet: const express = require( 'express' ); const router = require( 'express-promise-router' )(); let ...

Transmit information seamlessly between PHP and Dart

I'm currently working on establishing communication between Dart clientside and a PHP server side using AJAX. Since direct execution is not feasible, I compiled the Dart code to JavaScript and then hosted it on an Apache server. Although JSON data is ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

Seeking out all of the children associated with their parent using Jquery

Currently, I am utilizing Codeigniter and Jquery in conjunction with the AJAX method to retrieve data from two tables within my database by using a select join operation on the 'group' table and 'cat' table. Below is a description of t ...

Utilizing Ember to transmit models to Bootstrap Popovers

Seeking assistance from anyone familiar with utilizing Bootstrap for Ember components to help resolve an issue. I am trying to understand how to pass a model to the component when using {{bs-bind-popover}} <div {{bs-bind-popover templPop}}>Show pop ...

Troubleshooting the issue of Ajax POST not properly sending the model data to the controller in ASP.NET Core

I've been attempting to send POST data to my controller from a Kendo dialog event, but I keep encountering the issue of the model being null. Despite trying multiple solutions mentioned on StackOverflow, none have proven effective. Here is my Ajax ca ...

The Ajax contact form is not submitting the necessary POST data to the PHP script

After creating an html form with ajax: function confirmSendMail() { $(".send_contact").click(function(event){ event.preventDefault(); var name = $("#inputName").val(); var email = $("#inputEmail").val(); var pho ...

Issue with AngularJS script halting when reaching factory function that returns a promise

I have been working on a beginner project that is essentially a simple task manager (similar to those todo list projects). I created a user login page for this project and here is how it functions. There are two functions, siteLogin() for logging in, and ...

Include a new route in the Vue.js router dynamically during runtime

I am in the process of developing an application and I want to incorporate extensions into it. These extensions will have their own Vue components, views, and routes. Instead of rebuilding the entire app, I am looking for a way to dynamically add these new ...

Tips for implementing an onClick event within a NavBar component in a React application

Embarking on my first React project has been an exciting journey for me. I am relatively new to JavaScript, HTML, CSS, and the world of web app programming. My goal is to showcase some information upon clicking a button. In my main default component, App ...

Struggling to implement a Rock Paper Scissors game using HTML, CSS Bootstrap4, and JavaScript, specifically facing challenges in getting the function to select a new image

Recently, in my coding class, we were tasked with creating a program that would display images of dice and generate random numbers when the refresh button was clicked. To practice using querySelector and setAttribute, I decided to expand on the lesson by i ...

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Is the connection and callback order incorrect in Node.js and MQTT?

As I explore using the mqtt package for nodejs, I keep coming across code samples like the one below: const mqtt = require('mqtt') const client = mqtt.connect('mqtt://test.mosquitto.org') client.on('connect', function () { ...

Locating the specific row associated with a cell using jQuery

Iā€™m new to programming and currently learning JQuery. I have a query: if there is a button in a column attribute, and upon clicking the button in that cell, I want to retrieve the unique ID value for that cell. For example, if my attribute name is "app ...

Troubleshooting: HighCharts xAxis not displaying dates correctly when using JSON data

/* Analyzing Historical Performance */ document.addEventListener('DOMContentLoaded', function() { const lineChartUrl = 'https://bfc-dashboard-api.herokuapp.com/line_chart'; Highcharts.getJSON(lineChartUrl, function(data) { va ...

Why is it that my WebMethod consistently produces JSON responses?

Excuse me if this question is a bit basic, as it's not my usual expertise. I have a WebMethod that returns a String (string table=""). However, the Ajax return function always interprets it as a JSON Object like {"d":{...}}. My question is WHY am I ...

Leveraging jQuery for Crafting a Quiz with True or False Questions

Exploring the most effective approach to constructing a questionnaire. Find images below for reference. The current code setup is functional but becomes lengthy after just two questions. How can I streamline this code to minimize repetition? // prevent d ...

Navigating through hashed URLs with a Flexslider component

I have a website under construction that utilizes a flexslider, and I am looking to incorporate URL hash navigation. My goal is to extract the slide index based on the URL hash. I have examined the code for manual navigation where the index of the clicked ...