简体   繁体   中英

How do I SET a Cookie (header) with XMLHttpRequest in JavaScript?

I'm trying to set a Cookie in a XSS request using XMLHttpRequest.

I found the XMLHttpRequest Specification , and section 4.6.2-5 does seem to suggest that setting Cookie, Cookie2, and some other headers are not allowed, but I was hoping there was a work around.

My (jQuery) code is below, but the resulting query fails as the cookie is NOT set.

$.ajax( {
  type : "POST",
  url : URL,
  data: SOAP_INBOX_MAIL_QUERY,
  dataType : "xml",
  async: false,
  beforeSend : function(xhr) {  
    var cookie = credentials["COOKIE"];
    console.info( "adding cookie: "+ cookie );          
    xhr.setRequestHeader('Cookie', cookie);
  },
  success : function(data, textStatus, xmLHttpRequest){


  },
  error : function(xhr, ajaxOptions, thrownError) {
    credentials = null;
  }
});

This can be done. You need the following in the $.ajax call:

xhrFields: {
    withCredentials: true
}

(See the jQuery docs), and you'll also need the site you're making the request to to support CORS (they will at least need to allow you origin and also to set the Access-Control-Allow-Credentials HTTP header to true ).

There's no question it works. You can do it over HTTPS, with Basic Auth, etc. jQuery will send everything (the auth header, cookies) if you tell it to (xhrFields) and the site provides the right CORS headers. Don't give up!

出于安全原因,您将无法在XMLHTTPRequest期间修改标头。

如果您使用document.cookie设置cookie,那么当您发送请求时,cookie标头将包含它。

https://developer.mozilla.org/En/Server-Side_Access_Control

allow you origin and also to set the Access-Control-Allow-Credentials HTTP header to true

如果您的请求与jquery代码在同一个域中,则可以使用jquery cookies插件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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