ajax、fetch 跨域携带cookie

ajax、fetch 跨域携带cookie,第1张

原生ajax请求方式:

jquery的post方法请求:

服务器端设置

前后端分离,用nginx做请求跨域处理。用了fetch来替代ajax,访问正常,但是请求时没带cookie,就加了credentials: "include"

在后台配置

1、问题原因:cookie的作用域是domain本身以及domain下的所有子域名。

后端PHP用 setcookie 来设置网站的cookie,该函数的用法如下:

它的第五个参数$domain决定了cookie的作用域。作用域的限制使得setCookie失败

2、解决办法

前端电脑绑定host

webpack代理设置如下

开发时,浏览器访问 http://dev.bb.aa.ke.com:6666/

解决ajax发送请求无法设置cookie问题

前端jquery

let url = 'http://www.baidu.com'

let url1 = 'http://www.baidu.com'

let username = 'abc'

let password = 'abc'

$.ajax({

          url: url,

          type: 'post',

          data: {

            mobile: username,

            mobilepwd: password,

          },

          xhrFields: {

            withCredentials: true

          },

          dataType: 'json',

          success: function (res) {

            console.log(res)

            if (res.status == 1) {

              window.location.href = url

            }

          }

        })

前端vue

var $this = this

let url = 'http://www.baidu.com'

let data = {

    mobile:123,

    mobilepwd:123,

}

$this.$axios.defaults.withCredentials = true

$this.$axios.post(url,data)

  .then((res) =>{

    console.log(res.data)

  })

php后台设置

header('Access-Control-Allow-Origin:'.$_SERVER['HTTP_ORIGIN'])

header("Access-Control-Allow-Credentials: true")

解释两个header的作用

我们在客户端设置了withCredentials=true 参数,对应着,服务器端要通过在响应 header 中设置Access-Control-Allow-Credentials = true来运行客户端携带证书式的访问。通过对Credentials参数的设置,就可以保持跨域Ajax时传递的Cookie。

发送ajax请求,我们发现还会出现一个错误,提示我们Access-Control-Allow-Origin不能用*通配符。原因是:当服务器端Access-Control-Allow-Credentials = true时,参数Access-Control-Allow-Origin的值不能为'*'。

我们重新设置Access-Control-Allow-Origin的值,当服务器端接收到请求后,在返回响应时,把请求的域Origin填写到响应的Header信息里(即谁访问我,我允许谁)

什么是 credentials

credentials,即用户凭证,是指 cookie、HTTP身份验证和TLS客户端证书。需要注意的是,它不涉及代理身份验证或源标头。

XMLHttpRequest 的 withCredentials 属性

默认值为false。在获取同域资源时设置 withCredentials 没有影响。

ajax会自动带上同源的cookie,不会带上不同源的cookie

可以通过前端设置withCredentials为true, 后端设置Header的方式来让ajax自动带上不同源的cookie,但是这个属性对同源请求没有任何影响, 会被自动忽略。

true:在跨域请求时,会携带用户凭证

false:在跨域请求时,不会携带用户凭证;返回的 response 里也会忽略 cookie

规范文档中描述,它在特定情况下会报错

throws an InvalidStateError exception if state is not unsent or opened, or if the send() flag is set.

这里的 state 是指 XMLHttpRequest 的 readyState 属性,我们来简单回顾一下相关内容。

IE 10

原来,在IE10环境下,withCredentials 属性必须在open方法成功执行之后,send执行之前设置才可以,否则会报错。如果open方法执行失败了,设置 withCredentials 属性依然会报错。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11219245.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存