zoukankan      html  css  js  c++  java
  • javascript fetch 跨域请求时 session失效问题

    javascript 使用fetch进行跨域请求时默认是不带cookie的,所以会造成 session失效。

    fetch(url, {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify({
          data: options.data
        })
      })
    credentials: 'include' 可以是fetch 带上cookie。但是问题了来。
    原来在服务器端设置header (php 服务器)
        header("Access-Control-Allow-Origin: *");

    会报错:

    A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:8000' is therefore not allowed access.

    可以看到不允许 使用‘*’ 号了,那么就改成 访问域名(这里是本地调用所以是 http://localhost:8000)

    header("Access-Control-Allow-Origin: http://localhost:8000");

    改完后再次发送请求,还是报错

    Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:8000' is therefore not allowed access.

    说'Access-Control-Allow-Credentials 头必须是true,那么继续增加

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

    增加完后可以正常访问了,而且session也有了。

    ps: fetch 有个mode 是no-cors ,发现设置后返回的status是0,查资料后

    no-cors mode is only to CDN content, such as scripts, CSS and image, you cannot be used for getting data,response.status = 0 is right behavior

    no-cors 模式只能用来获取CDN内容,比如脚本,css文件和图片,如果用来获取数据比如json格式就会返回status=0

     
  • 相关阅读:
    windows定时任务schtasks命令详细解
    TCP/IP 详解7 Ping指令
    Vue JSX、自定义 v-model
    DOM 元素的循环遍历
    关于 Blob
    Vue.nextTick 的应用解析
    弹窗组件及其回调函数
    krry-transfer ⏤ 基于 element 的升级版穿梭框组件发布到 npm 啦
    防抖与节流 & 若每个请求必须发送,如何平滑地获取最后一个接口返回的数据
    Java 单文件、多文件上传 / 实现上传进度条
  • 原文地址:https://www.cnblogs.com/neverleave/p/6533133.html
Copyright © 2011-2022 走看看