Send cookie in HTTP POST Request in javascript
我试图通过javascript向服务器(这是一个REST服务)发出POST请求,并在我的请求中我想发送一个cookie。我的下面的代码不起作用,因为我无法在服务器上收到cookie side.Below是我的客户端和服务器端代码。
客户端 :
1 2 3 4 5 6 7 8 9 10 11 | 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); |
服务器端:
1 2 3 4 5 | 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 } |
查看文档:
Terminate these steps if header is a case-insensitive match for one of the following headers …
Cookie
您无法使用XHR显式设置Cookie标头。
看起来你正在做一个跨源请求(你使用的是绝对URI)。
您可以设置
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.
这样:
1 | client.withCredentials = true; |
这仅在
如果做不到这一点,您将不得不在其他地方对要放入cookie的数据进行编码。
这也可以用更现代的
1 2 3 4 5 | fetch(url, { method: 'POST', credentials: 'include' //other options }).then(response => console.log("Response status:", response.status)); |