arpit joshi
arpit joshi

Reputation: 2134

Send cookie in HTTP POST Request in javascript

I am trying to make a POST request to the server (Which is a REST service)via javascript,and in my request i want to send a cookie.My below code is not working ,as I am not able to receive cookie at the server side.Below are my client side and server side code.

Client side :

var client = new XMLHttpRequest();
          var request_data=JSON.stringify(data);
var endPoint="http://localhost:8080/pcap";
var cookie="session=abc";
          client.open("POST", endPoint, false);//This Post will become put 
          client.setRequestHeader("Accept", "application/json");
          client.setRequestHeader("Content-Type","application/json");

          client.setRequestHeader("Set-Cookie","session=abc");
          client.setRequestHeader("Cookie",cookie);
          client.send(request_data);

Server Side:

public @ResponseBody ResponseEntity getPcap(HttpServletRequest request,@RequestBody PcapParameters pcap_params ){

Cookie cookies[]=request.getCookies();//Its coming as NULL
        String cook=request.getHeader("Cookie");//Its coming as NULL
}

Upvotes: 18

Views: 97947

Answers (2)

PDStat
PDStat

Reputation: 5825

This can also be done with the more modern fetch

fetch(url, {
    method: 'POST',
    credentials: 'include'
    //other options
}).then(response => console.log("Response status: ", response.status));

Upvotes: 7

Quentin
Quentin

Reputation: 943142

See the documentation:

Terminate these steps if header is a case-insensitive match for one of the following headers … Cookie

You cannot explicitly set a Cookie header using XHR.


It looks like you are making a cross origin request (you are using an absolute URI).

You can set withCredentials to include cookies.

True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.

Such:

client.withCredentials = true;

This will only work if http://localhost:8080 has set a cookie using one of the supported methods (such as in an HTTP Set-Cookie response header).


Failing that, you will have to encode the data you wanted to put in the cookie somewhere else.

Upvotes: 14

Related Questions