Send cookie in HTTP POST Request in javascript

陌路散爱 提交于 2019-11-30 02:54:39

问题


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
}

回答1:


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.




回答2:


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));


来源:https://stackoverflow.com/questions/35733138/send-cookie-in-http-post-request-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!