简体   繁体   English

在javascript中发送HTTP POST请求中的cookie

[英]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. 我试图通过javascript向服务器(这是一个REST服务)发出POST请求,并在我的请求中我想发送一个cookie。我的下面的代码无法正常工作,因为我无法在服务器上收到cookie side.Below是我的客户端和服务器端代码。

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
}

See the documentation : 查看文档

Terminate these steps if header is a case-insensitive match for one of the following headers … Cookie 如果header是以下标题之一的不区分大小写的匹配,请终止这些步骤... Cookie

You cannot explicitly set a Cookie header using XHR. 您无法使用XHR显式设置Cookie标头。


It looks like you are making a cross origin request (you are using an absolute URI). 看起来你正在做一个跨源请求(你使用的是绝对URI)。

You can set withCredentials to include cookies. 您可以设置withCredentials以包含Cookie。

True when user credentials are to be included in a cross-origin request. 当用户凭据包含在跨源请求中时为True。 False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. 如果要在跨源请求中排除它们以及在响应中忽略cookie,则为false。 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). 这仅在http://localhost:8080使用其中一种受支持的方法(例如在HTTP Set-Cookie 响应头中)设置cookie时才有效。


Failing that, you will have to encode the data you wanted to put in the cookie somewhere else. 如果做不到这一点,您将不得不在其他地方对要放入cookie的数据进行编码。

This can also be done with the more modern fetch 这也可以通过更现代的fetch来完成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM