如何在JavaScript中使用XMLHttpRequest设置Cookie(标题)? [英] How do I SET a Cookie (header) with XMLHttpRequest in JavaScript?

查看:511
本文介绍了如何在JavaScript中使用XMLHttpRequest设置Cookie(标题)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用XMLHttpRequest在XSS请求中设置Cookie。

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

我找到了 XMLHttpRequest规范,4.6.2-5节似乎建议不允许设置Cookie,Cookie2和其他一些标题,但我希望那里是一个解决方法。

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.

我的(jQuery)代码如下,但由于未设置cookie,结果查询失败。

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


推荐答案

这可以做到。 $ .ajax调用中需要以下内容:

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

xhrFields: {
    withCredentials: true
}

(请参阅jQuery文档),您还需要提供请求的网站支持CORS(他们至少需要允许你来源,并且还要将 Access-Control-Allow-Credentials HTTP标头设置为 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).

毫无疑问它有效。您可以通过HTTPS,使用Basic Auth等来执行此操作。如果您告诉它(xhrFields)并且站点提供正确的CORS标头,jQuery将发送所有内容(auth标头,cookie)。不要放弃!

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!

这篇关于如何在JavaScript中使用XMLHttpRequest设置Cookie(标题)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆