跨域POST请求不发送cookie Ajax Jquery [英] Cross domain POST request is not sending cookie Ajax Jquery

查看:45
本文介绍了跨域POST请求不发送cookie Ajax Jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎已经在 stackoverflow 上讨论过类似的内容,但我找不到完全相同的内容.

Seems that something similar already has been discussed on stackoverflow, but i could not find exactly the same.

我正在尝试使用 CORS(跨源资源共享)发送 Cookie,但它不起作用.

I am trying to send Cookie with CORS(Cross-origin resource sharing), but it is not working.

这是我的代码.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'json',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

我在请求 HEADER 中没有看到这个 cookie.

I dont see this cookie in request HEADER.

推荐答案

您无法通过 JavaScript 在 CORS 请求上设置或读取 cookie.尽管 CORS 允许跨域请求,但 cookie 仍受浏览器的同源策略约束,这意味着只有来自同一源的页面才能读取/写入 cookie.withCredentials 仅表示远程主机设置的任何 cookie 都会发送到该远程主机.您必须使用 Set-Cookie 标头从远程服务器设置 cookie.

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

这篇关于跨域POST请求不发送cookie Ajax Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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